fix sort by internaldate if the internaldate does not have the expected
[squirrelmail.git] / functions / imap_messages.php
1 <?php
2
3 /**
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 */
16
17 /**
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 */
25 function sqimap_messages_copy ($imap_stream, $start, $end, $mailbox) {
26 $read = sqimap_run_command ($imap_stream, "COPY $start:$end " . sqimap_encode_mailbox_name($mailbox), true, $response, $message, TRUE);
27 }
28
29 /**
30 * copy a range of messages ($id) to another mailbox ($mailbox)
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
35 */
36 function sqimap_msgs_list_copy ($imap_stream, $id, $mailbox) {
37 $msgs_id = sqimap_message_list_squisher($id);
38 $read = sqimap_run_command ($imap_stream, "COPY $msgs_id " . sqimap_encode_mailbox_name($mailbox), true, $response, $message, TRUE);
39 }
40
41 /**
42 * move a range of messages ($id) to another mailbox. Deletes the originals.
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
47 */
48 function sqimap_msgs_list_move ($imap_stream, $id, $mailbox) {
49 $msgs_id = sqimap_message_list_squisher($id);
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);
52 }
53
54
55 /**
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 */
64 function sqimap_messages_delete ($imap_stream, $start, $end, $mailbox, $bypass_trash=false) {
65 global $move_to_trash, $trash_folder, $auto_expunge;
66
67 if (($move_to_trash == true) && ($bypass_trash != true) &&
68 (sqimap_mailbox_exists($imap_stream, $trash_folder) && ($mailbox != $trash_folder))) {
69 sqimap_messages_copy ($imap_stream, $start, $end, $trash_folder);
70 }
71 sqimap_messages_flag ($imap_stream, $start, $end, "Deleted", true);
72 }
73
74 function sqimap_msgs_list_delete ($imap_stream, $mailbox, $id, $bypass_trash=false) {
75 global $move_to_trash, $trash_folder;
76 $msgs_id = sqimap_message_list_squisher($id);
77 if (($move_to_trash == true) && ($bypass_trash != true) &&
78 (sqimap_mailbox_exists($imap_stream, $trash_folder) && ($mailbox != $trash_folder)) ) {
79 $read = sqimap_run_command ($imap_stream, "COPY $msgs_id " . sqimap_encode_mailbox_name($trash_folder), true, $response, $message, TRUE);
80 }
81 $read = sqimap_run_command ($imap_stream, "STORE $msgs_id +FLAGS (\\Deleted)", true, $response, $message, TRUE);
82 }
83
84
85 /**
86 * Sets the specified messages with specified flag
87 */
88 function sqimap_messages_flag ($imap_stream, $start, $end, $flag, $handle_errors) {
89 $read = sqimap_run_command ($imap_stream, "STORE $start:$end +FLAGS (\\$flag)", $handle_errors, $response, $message, TRUE);
90 }
91
92 function sqimap_toggle_flag($imap_stream, $id, $flag, $set, $handle_errors) {
93 $msgs_id = sqimap_message_list_squisher($id);
94 $set_string = ($set ? '+' : '-');
95 $read = sqimap_run_command ($imap_stream, "STORE $msgs_id ".$set_string."FLAGS ($flag)", $handle_errors, $response, $message, TRUE);
96 }
97
98 /** @deprecated */
99 function sqimap_get_small_header ($imap_stream, $id, $sent) {
100 $res = sqimap_get_small_header_list($imap_stream, $id, $sent);
101 return $res[0];
102 }
103
104 /**
105 * Sort the message list and crunch to be as small as possible
106 * (overflow could happen, so make it small if possible)
107 */
108 function sqimap_message_list_squisher($messages_array) {
109 if( !is_array( $messages_array ) ) {
110 return $messages_array;
111 }
112
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 }
129 return $msgs_str;
130 }
131
132 /**
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
139 */
140 function sqimap_get_sort_order ($imap_stream, $sSortField = 'UID',$reverse) {
141 global $default_charset,
142 $sent_folder;
143
144 $id = array();
145 $sort_test = array();
146 $sort_query = '';
147
148 if ($sSortField == 'UID') {
149 $query = "SEARCH UID 1:*";
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)) {
153 $id = preg_split("/ /", trim($regs[1]));
154 }
155 }
156 if (!preg_match("/OK/", $response)) {
157 $id = false;
158 }
159 $id = array_reverse($id);
160 return $id;
161 }
162 if ($sSortField) {
163 if ($reverse) {
164 $sSortField = 'REVERSE '.$sSortField;
165 }
166 $query = "SORT ($sSortField) ".strtoupper($default_charset).' ALL';
167 $sort_test = sqimap_run_command ($imap_stream, $query, true, $response, $message, TRUE);
168 }
169 if (isset($sort_test[0])) {
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 }
175 }
176 }
177 if (!preg_match("/OK/", $response)) {
178 return false;
179 } else {
180 return $id;
181 }
182 }
183
184 /**
185 * Retrieves an array with a sorted uid list. Sorting is done by SquirrelMail
186 *
187 * @param resource $imap_stream IMAP socket connection
188 * @param string $sSortField Field to sort on
189 * @param bool $reverse Reverse order search
190 * @return array $aUid sorted uid list
191 */
192 function get_squirrel_sort ($imap_stream, $sSortField, $reverse = false) {
193
194 if ($sSortField == 'UID') {
195 // FIX ME: this is not needed. Try to find another way to solve this
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 }
213 $aUid = array();
214 $walk = false;
215 switch ($sSortField) {
216 // natcasesort section
217 case 'FROM':
218 case 'TO':
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;
226 }
227 // nobreak
228 case 'SUBJECT':
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 }
237 foreach ($msgs as $item) {
238 $aUid[$item['ID']] = $item[$sSortField];
239 }
240 natcasesort($aUid);
241 $aUid = array_keys($aUid);
242 if ($reverse) {
243 array_reverse($aUid);
244 }
245 break;
246 // \natcasesort section
247 // sort_numeric section
248 case 'DATE':
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;
255 }
256 // nobreak;
257 case 'RFC822.SIZE':
258 if(!$walk) {
259 // redefine $sSortField to maintain the same namespace between
260 // server-side sorting and squirrelmail sorting
261 $sSortField = 'SIZE';
262 }
263 foreach ($msgs as $item) {
264 $aUid[$item['ID']] = (isset($item[$sSortField])) ? $item[$sSortField] : 0;
265 }
266 if ($reverse) {
267 arsort($aUid,SORT_NUMERIC);
268 } else {
269 asort($aUid, SORT_NUMERIC);
270 }
271 $aUid = array_keys($aUid);
272 break;
273 // \sort_numeric section
274 case 'UID':
275 $aUid = array_reverse($msgs);
276 break;
277 }
278 return $aUid;
279 }
280
281 /**
282 * Returns an indent array for printMessageinfo()
283 * This represents the amount of indent needed (value),
284 * for this message number (key)
285 */
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 */
307 function get_parent_level ($thread_new) {
308 $parent = '';
309 $child = '';
310 $cutoff = 0;
311
312 /*
313 * loop through the threads and take unwanted characters out
314 * of the thread string then chop it up
315 */
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);
320 }
321 $indent_array = array();
322 if (!$thread_new) {
323 $thread_new = array();
324 }
325 /* looping through the parts of one message thread */
326
327 for ($i=0;$i<count($thread_new);$i++) {
328 /* first grab the parent, it does not indent */
329
330 if (isset($thread_new[$i][0])) {
331 if (preg_match("/(\d+)/", $thread_new[$i][0], $regs)) {
332 $parent = $regs[1];
333 }
334 }
335 $indent_array[$parent] = 0;
336
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 */
342 $level = 0;
343 $spaces = array();
344 $spaces_total = 0;
345 $indent = 0;
346 $fake = FALSE;
347 for ($k=1,$iCnt=count($thread_new[$i])-1;$k<$iCnt;++$k) {
348 $chars = count_chars($thread_new[$i][$k], 1);
349 if (isset($chars['40'])) { /* testing for ( */
350 $level += $chars['40'];
351 }
352 if (isset($chars['41'])) { /* testing for ) */
353 $level -= $chars['41'];
354 $spaces[$level] = 0;
355 /* if we were faking lets stop, this portion
356 * of the thread is over
357 */
358 if ($level == $cutoff) {
359 $fake = FALSE;
360 }
361 }
362 if (isset($chars['32'])) { /* testing for space */
363 if (!isset($spaces[$level])) {
364 $spaces[$level] = 0;
365 }
366 $spaces[$level] += $chars['32'];
367 }
368 for ($x=0;$x<=$level;$x++) {
369 if (isset($spaces[$x])) {
370 $spaces_total += $spaces[$x];
371 }
372 }
373 $indent = $level + $spaces_total;
374 /* must have run into a message that broke the thread
375 * so we are adjusting for that portion
376 */
377 if ($fake == TRUE) {
378 $indent = $indent +1;
379 }
380 if (preg_match("/(\d+)/", $thread_new[$i][$k], $regs)) {
381 $child = $regs[1];
382 }
383 /* the thread must be broken if $indent == 0
384 * so indent the message once and start faking it
385 */
386 if ($indent == 0) {
387 $indent = 1;
388 $fake = TRUE;
389 $cutoff = $level;
390 }
391 /* dont need abs but if indent was negative
392 * errors would occur
393 */
394 $indent_array[$child] = ($indent < 0) ? 0 : $indent;
395 $spaces_total = 0;
396 }
397 }
398 return $indent_array;
399 }
400
401
402 /**
403 * Returns an array with each element as a string representing one
404 * message-thread as returned by the IMAP server.
405 */
406 function get_thread_sort ($imap_stream) {
407 global $thread_new, $sort_by_ref, $default_charset, $server_sort_array, $indent_array;
408 if (sqsession_is_registered('thread_new')) {
409 sqsession_unregister('thread_new');
410 }
411 if (sqsession_is_registered('indent_array')) {
412 sqsession_unregister('indent_array');
413 }
414 if (sqsession_is_registered('server_sort_array')) {
415 sqsession_unregister('server_sort_array');
416 }
417 $thread_temp = array ();
418 if ($sort_by_ref == 1) {
419 $sort_type = 'REFERENCES';
420 } else {
421 $sort_type = 'ORDEREDSUBJECT';
422 }
423 $query = "THREAD $sort_type ".strtoupper($default_charset)." ALL";
424 $thread_test = sqimap_run_command ($imap_stream, $query, true, $response, $message, TRUE);
425 if (isset($thread_test[0])) {
426 for ($i=0,$iCnt=count($thread_test);$i<$iCnt;++$i) {
427 if (preg_match("/^\* THREAD (.+)$/", $thread_test[$i], $regs)) {
428 $thread_list = trim($regs[1]);
429 break;
430 }
431 }
432 } else {
433 $thread_list = "";
434 }
435 if (!preg_match("/OK/", $response)) {
436 $server_sort_array = 'no';
437 return $server_sort_array;
438 }
439 if (isset($thread_list)) {
440 $thread_temp = preg_split("//", $thread_list, -1, PREG_SPLIT_NO_EMPTY);
441 }
442
443 $char_count = count($thread_temp);
444 $counter = 0;
445 $thread_new = array();
446 $k = 0;
447 $thread_new[0] = "";
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++) {
460 if ($thread_temp[$i] != ')' && $thread_temp[$i] != '(') {
461 $thread_new[$k] = $thread_new[$k] . $thread_temp[$i];
462 } elseif ($thread_temp[$i] == '(') {
463 $thread_new[$k] .= $thread_temp[$i];
464 $counter++;
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 }
475 }
476 }
477 sqsession_register($thread_new, 'thread_new');
478 $thread_new = array_reverse($thread_new);
479 /* place the threads after each other in one string */
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);
484 $server_sort_array = $thread_list;
485
486 $indent_array = get_parent_level ($thread_new);
487 sqsession_register($indent_array, 'indent_array');
488
489 sqsession_register($server_sort_array, 'server_sort_array');
490 return $thread_list;
491 }
492
493
494 function elapsedTime($start) {
495 $stop = gettimeofday();
496 $timepassed = 1000000 * ($stop['sec'] - $start['sec']) + $stop['usec'] - $start['usec'];
497 return $timepassed;
498 }
499
500 // only used in sqimap_get_small_header_list
501 function parseString($read,&$i) {
502 $char = $read{$i};
503 $s = '';
504 if ($char == '"') {
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 }
519 } else if ($char == '{') {
520 $lit_cnt = '';
521 ++$i;
522 $iPos = strpos($read,'}',$i);
523 if ($iPos) {
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 */
533 $i += 3; /* } + \r + \n */
534 $s = '';
535 }
536 } else {
537 return false;
538 }
539 ++$i;
540 return $s;
541 }
542
543 // only used in sqimap_get_small_header_list
544 function 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
557 function sqimap_get_small_header_list ($imap_stream, $msg_list, $show_num=false,
558 $aHeaderFields = array('Date', 'To', 'Cc', 'From', 'Subject', 'X-Priority', 'Content-Type'),
559 $aFetchItems = array('FLAGS', 'UID', 'RFC822.SIZE', 'INTERNALDATE')) {
560
561 global $squirrelmail_language, $color, $data_dir, $username, $imap_server_type;
562 global $allow_server_sort;
563
564 $messages = array();
565 $read_list = array();
566
567 /* Get the small headers for each message in $msg_list */
568 if ($show_num != '999999' && $show_num != '*' ) {
569 $msgs_str = sqimap_message_list_squisher($msg_list);
570 /*
571 * We need to return the data in the same order as the caller supplied
572 * in $msg_list, but IMAP servers are free to return responses in
573 * whatever order they wish... So we need to re-sort manually
574 */
575 for ($i = 0; $i < sizeof($msg_list); $i++) {
576 $messages["$msg_list[$i]"] = array();
577 }
578 } else {
579 $msgs_str = '1:*';
580 }
581
582
583
584 /*
585 * Create the query
586 */
587
588 $internaldate = getPref($data_dir, $username, 'internal_date_sort');
589 if (($i = array_search('INTERNALDATE',$aFetchItems,true)) !== false && $internaldate == false) {
590 unset($aFetchItems[$i]);
591 }
592 $sFetchItems = '';
593 $query = "FETCH $msgs_str (";
594 if (count($aFetchItems)) {
595 $sFetchItems = implode(' ',$aFetchItems);
596 }
597 if (count($aHeaderFields)) {
598 $sHeaderFields = implode(' ',$aHeaderFields);
599 $sFetchItems .= ' BODY.PEEK[HEADER.FIELDS ('.$sHeaderFields.')]';
600 }
601 $query .= trim($sFetchItems) . ')';
602 $read_list = sqimap_run_command_list ($imap_stream, $query, true, $response, $message, TRUE);
603 $i = 0;
604
605 foreach ($read_list as $r) {
606 // use unset because we do isset below
607 $read = implode('',$r);
608
609 /*
610 * #id<space>FETCH<space>(
611 */
612
613 /* extract the message id */
614 $i_space = strpos($read,' ',2);
615 $id = substr($read,2,$i_space-2);
616 $fetch = substr($read,$i_space+1,5);
617 if (!is_numeric($id) && $fetch !== 'FETCH') {
618 set_up_language($squirrelmail_language);
619 echo '<br><b><font color=$color[2]>' .
620 _("ERROR : Could not complete request.") .
621 '</b><br>' .
622 _("Unknown response from IMAP server: ") . ' 1.' .
623 htmlspecialchars($read) . "</font><br>\n";
624 break;
625 }
626 $i = strpos($read,'(',$i_space+5);
627 $read = substr($read,$i+1);
628 $i_len = strlen($read);
629 $i = 0;
630 while ($i < $i_len && $i !== false) {
631 /* get argument */
632 $read = trim(substr($read,$i));
633 $i_len = strlen($read);
634 $i = strpos($read,' ');
635 $arg = substr($read,0,$i);
636 ++$i;
637 switch ($arg)
638 {
639 case 'UID':
640 $i_pos = strpos($read,' ',$i);
641 if (!$i_pos) {
642 $i_pos = strpos($read,')',$i);
643 }
644 if ($i_pos) {
645 $unique_id = substr($read,$i,$i_pos-$i);
646 $i = $i_pos+1;
647 } else {
648 break 3;
649 }
650 break;
651 case 'FLAGS':
652 $flags = parseArray($read,$i);
653 if (!$flags) break 3;
654 $aFlags = array();
655 foreach ($flags as $flag) {
656 $flag = strtolower($flag);
657 $aFlags[$flag] = true;
658 }
659 $msg['FLAGS'] = $aFlags;
660 break;
661 case 'RFC822.SIZE':
662 $i_pos = strpos($read,' ',$i);
663 if (!$i_pos) {
664 $i_pos = strpos($read,')',$i);
665 }
666 if ($i_pos) {
667 $msg['SIZE'] = substr($read,$i,$i_pos-$i);
668 $i = $i_pos+1;
669 } else {
670 break 3;
671 }
672
673 break;
674 case 'INTERNALDATE':
675 $msg['INTERNALDATE'] = str_replace(' ', ' ',parseString($read,$i));
676 break;
677 case 'BODY.PEEK[HEADER.FIELDS':
678 case 'BODY[HEADER.FIELDS':
679 $i = strpos($read,'{',$i);
680 $header = parseString($read,$i);
681 if ($header === false) break 2;
682 /* First we replace all \r\n by \n, and unfold the header */
683 $hdr = trim(str_replace(array("\r\n", "\n\t", "\n "),array("\n", ' ', ' '), $header));
684 /* Now we can make a new header array with */
685 /* each element representing a headerline */
686 $hdr = explode("\n" , $hdr);
687 foreach ($hdr as $line) {
688 $pos = strpos($line, ':');
689 if ($pos > 0) {
690 $field = strtolower(substr($line, 0, $pos));
691 if (!strstr($field,' ')) { /* valid field */
692 $value = trim(substr($line, $pos+1));
693 switch($field)
694 {
695 case 'to': $msg['TO'] = $value; break;
696 case 'cc': $msg['CC'] = $value; break;
697 case 'from': $msg['FROM'] = $value; break;
698 case 'date':
699 $msg['DATE'] = str_replace(' ', ' ', $value);
700 break;
701 case 'x-priority': $msg['PRIORITY'] = $value; break;
702 case 'subject': $msg['SUBJECT'] = $value; break;
703 case 'content-type':
704 $type = $value;
705 if ($pos = strpos($type, ";")) {
706 $type = substr($type, 0, $pos);
707 }
708 $type = explode("/", $type);
709 if(!is_array($type)) {
710 $msg['TYPE0'] = 'text';
711 $msg['TYPE1'] = 'plain';
712 }
713 break;
714 default: break;
715 }
716 }
717 }
718 }
719 break;
720 default:
721 ++$i;
722 break;
723 }
724 }
725 $msgi ="$unique_id";
726 $msg['ID'] = $unique_id;
727
728 $messages[$msgi] = $msg;
729 ++$msgi;
730 }
731 array_reverse($messages);
732 return $messages;
733 }
734
735 /**
736 * Returns a message array with all the information about a message.
737 * See the documentation folder for more information about this array.
738 */
739 function sqimap_get_message ($imap_stream, $id, $mailbox) {
740 // typecast to int to prohibit 1:* msgs sets
741 $id = (int) $id;
742 $flags = array();
743 $read = sqimap_run_command ($imap_stream, "FETCH $id (FLAGS BODYSTRUCTURE)", true, $response, $message, TRUE);
744 if ($read) {
745 if (preg_match('/.+FLAGS\s\((.*)\)\s/AUi',$read[0],$regs)) {
746 if (trim($regs[1])) {
747 $flags = preg_split('/ /', $regs[1],-1,'PREG_SPLIT_NI_EMPTY');
748 }
749 }
750 } else {
751 /* the message was not found, maybe the mailbox was modified? */
752 global $sort, $startMessage, $color;
753
754 $errmessage = _("The server couldn't find the message you requested.") .
755 '<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).");
756 /* this will include a link back to the message list */
757 error_message($errmessage, $mailbox, $sort, (int) $startMessage, $color);
758 exit;
759 }
760 $bodystructure = implode('',$read);
761 $msg = mime_structure($bodystructure,$flags);
762 $read = sqimap_run_command ($imap_stream, "FETCH $id BODY[HEADER]", true, $response, $message, TRUE);
763 $rfc822_header = new Rfc822Header();
764 $rfc822_header->parseHeader($read);
765 $msg->rfc822_header = $rfc822_header;
766 return $msg;
767 }
768
769 ?>