fix for non server side sorting on internal date
[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 * @param mixed $key UNDOCUMENTED
191 * @return array $id sorted uid list
192 */
193 function get_squirrel_sort ($imap_stream, $sSortField, $reverse = false) {
194
195 if ($sSortField == 'UID') {
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 switch ($sSortField) {
214 case 'FROM':
215 array_walk($msgs, create_function('&$v,&$k',
216 '$from = parseAddress($v["FROM"]);
217 $v["FROM"] = ($from[0][1]) ? decodeHeader($from[0][1]):$from[0][0];'));
218 foreach ($msgs as $item) {
219 $msort["$item[ID]"] = (isset($item['FROM'])) ? $item['FROM'] : '';
220 }
221
222 natcasesort($msort);
223 $msort = array_keys($msort);
224 if ($reverse) {
225 array_reverse($msort);
226 }
227 break;
228 case 'TO':
229 array_walk($msgs, create_function('&$v,&$k',
230 '$from = parseAddress($v["TO"]);
231 $v["TO"] = ($from[0][1]) ? decodeHeader($from[0][1]):$from[0][0];'));
232 foreach ($msgs as $item) {
233 $msort["$item[ID]"] = (isset($item['TO'])) ? $item['TO'] : '';
234 }
235
236 natcasesort($msort);
237 $msort = array_keys($msort);
238 if ($reverse) {
239 array_reverse($msort);
240 }
241 break;
242
243 case 'SUBJECT':
244 array_walk($msgs, create_function('&$v,&$k',
245 '$v["SUBJECT"] = strtolower(decodeHeader(trim($v["SUBJECT"])));
246 $v["SUBJECT"] = (preg_match("/^(vedr|sv|re|aw|\[\w\]):\s*(.*)$/si", $v["SUBJECT"], $matches)) ?
247 $matches[2] : $v["SUBJECT"];'));
248 foreach ($msgs as $item) {
249 $msort["$item[ID]"] = $item['SUBJECT'];
250 }
251 natcasesort($msort);
252 $msort = array_keys($msort);
253 if ($reverse) {
254 array_reverse($msort);
255 }
256 break;
257 case 'DATE':
258 array_walk($msgs, create_function('&$v,$k',
259 '$v["DATE"] = getTimeStamp(explode(" ",$v["DATE"]));'));
260 foreach ($msgs as $item) {
261 $msort[$item['ID']] = $item['DATE'];
262 }
263 if ($reverse) {
264 arsort($msort,SORT_NUMERIC);
265 } else {
266 asort( $msort, SORT_NUMERIC);
267 }
268 $msort = array_keys($msort);
269 break;
270 case 'RFC822.SIZE':
271 case 'INTERNALDATE':
272 //array_walk($msgs, create_function('&$v,$k',
273 // '$v["RFC822.SIZE"] = getTimeStamp(explode(" ",$v["RFC822.SIZE"]));'));
274 foreach ($msgs as $item) {
275 $msort[$item['ID']] = $item[$sSortField];
276 }
277 if ($reverse) {
278 arsort($msort,SORT_NUMERIC);
279 } else {
280 asort($msort, SORT_NUMERIC);
281 }
282 $msort = array_keys($msort);
283 break;
284 case 'UID':
285 $msort = array_reverse($msgs);
286 break;
287 }
288 return $msort;
289 }
290
291 /**
292 * Returns an indent array for printMessageinfo()
293 * This represents the amount of indent needed (value),
294 * for this message number (key)
295 */
296 function get_parent_level ($thread_new) {
297 $parent = '';
298 $child = '';
299 $cutoff = 0;
300
301 /* loop through the threads and take unwanted characters out
302 of the thread string then chop it up
303 */
304 for ($i=0;$i<count($thread_new);$i++) {
305 $thread_new[$i] = preg_replace("/\s\(/", "(", $thread_new[$i]);
306 $thread_new[$i] = preg_replace("/(\d+)/", "$1|", $thread_new[$i]);
307 $thread_new[$i] = preg_split("/\|/", $thread_new[$i], -1, PREG_SPLIT_NO_EMPTY);
308 }
309 $indent_array = array();
310 if (!$thread_new) {
311 $thread_new = array();
312 }
313 /* looping through the parts of one message thread */
314
315 for ($i=0;$i<count($thread_new);$i++) {
316 /* first grab the parent, it does not indent */
317
318 if (isset($thread_new[$i][0])) {
319 if (preg_match("/(\d+)/", $thread_new[$i][0], $regs)) {
320 $parent = $regs[1];
321 }
322 }
323 $indent_array[$parent] = 0;
324
325 /* now the children, checking each thread portion for
326 ),(, and space, adjusting the level and space values
327 to get the indent level
328 */
329 $level = 0;
330 $spaces = array();
331 $spaces_total = 0;
332 $indent = 0;
333 $fake = FALSE;
334 for ($k=1;$k<(count($thread_new[$i]))-1;$k++) {
335 $chars = count_chars($thread_new[$i][$k], 1);
336 if (isset($chars['40'])) { /* testing for ( */
337 $level = $level + $chars['40'];
338 }
339 if (isset($chars['41'])) { /* testing for ) */
340 $level = $level - $chars['41'];
341 $spaces[$level] = 0;
342 /* if we were faking lets stop, this portion
343 of the thread is over
344 */
345 if ($level == $cutoff) {
346 $fake = FALSE;
347 }
348 }
349 if (isset($chars['32'])) { /* testing for space */
350 if (!isset($spaces[$level])) {
351 $spaces[$level] = 0;
352 }
353 $spaces[$level] = $spaces[$level] + $chars['32'];
354 }
355 for ($x=0;$x<=$level;$x++) {
356 if (isset($spaces[$x])) {
357 $spaces_total = $spaces_total + $spaces[$x];
358 }
359 }
360 $indent = $level + $spaces_total;
361 /* must have run into a message that broke the thread
362 so we are adjusting for that portion
363 */
364 if ($fake == TRUE) {
365 $indent = $indent +1;
366 }
367 if (preg_match("/(\d+)/", $thread_new[$i][$k], $regs)) {
368 $child = $regs[1];
369 }
370 /* the thread must be broken if $indent == 0
371 so indent the message once and start faking it
372 */
373 if ($indent == 0) {
374 $indent = 1;
375 $fake = TRUE;
376 $cutoff = $level;
377 }
378 /* dont need abs but if indent was negative
379 errors would occur
380 */
381 $indent_array[$child] = abs($indent);
382 $spaces_total = 0;
383 }
384 }
385 return $indent_array;
386 }
387
388
389 /**
390 * Returns an array with each element as a string representing one
391 * message-thread as returned by the IMAP server.
392 */
393 function get_thread_sort ($imap_stream) {
394 global $thread_new, $sort_by_ref, $default_charset, $server_sort_array, $indent_array;
395 if (sqsession_is_registered('thread_new')) {
396 sqsession_unregister('thread_new');
397 }
398 if (sqsession_is_registered('indent_array')) {
399 sqsession_unregister('indent_array');
400 }
401 if (sqsession_is_registered('server_sort_array')) {
402 sqsession_unregister('server_sort_array');
403 }
404 $thread_temp = array ();
405 if ($sort_by_ref == 1) {
406 $sort_type = 'REFERENCES';
407 }
408 else {
409 $sort_type = 'ORDEREDSUBJECT';
410 }
411 $query = "THREAD $sort_type ".strtoupper($default_charset)." ALL";
412 $thread_test = sqimap_run_command ($imap_stream, $query, true, $response, $message, TRUE);
413 if (isset($thread_test[0])) {
414 for ($i=0,$iCnt=count($thread_test);$i<$iCnt;++$i) {
415 if (preg_match("/^\* THREAD (.+)$/", $thread_test[$i], $regs)) {
416 $thread_list = trim($regs[1]);
417 break;
418 }
419 }
420 }
421 else {
422 $thread_list = "";
423 }
424 if (!preg_match("/OK/", $response)) {
425 $server_sort_array = 'no';
426 return $server_sort_array;
427 }
428 if (isset($thread_list)) {
429 $thread_temp = preg_split("//", $thread_list, -1, PREG_SPLIT_NO_EMPTY);
430 }
431 $char_count = count($thread_temp);
432 $counter = 0;
433 $thread_new = array();
434 $k = 0;
435 $thread_new[0] = "";
436 for ($i=0;$i<$char_count;$i++) {
437 if ($thread_temp[$i] != ')' && $thread_temp[$i] != '(') {
438 $thread_new[$k] = $thread_new[$k] . $thread_temp[$i];
439 }
440 elseif ($thread_temp[$i] == '(') {
441 $thread_new[$k] .= $thread_temp[$i];
442 $counter++;
443 }
444 elseif ($thread_temp[$i] == ')') {
445 if ($counter > 1) {
446 $thread_new[$k] .= $thread_temp[$i];
447 $counter = $counter - 1;
448 }
449 else {
450 $thread_new[$k] .= $thread_temp[$i];
451 $k++;
452 $thread_new[$k] = "";
453 $counter = $counter - 1;
454 }
455 }
456 }
457 sqsession_register($thread_new, 'thread_new');
458 $thread_new = array_reverse($thread_new);
459 $thread_list = implode(" ", $thread_new);
460 $thread_list = str_replace("(", " ", $thread_list);
461 $thread_list = str_replace(")", " ", $thread_list);
462 $thread_list = preg_split("/\s/", $thread_list, -1, PREG_SPLIT_NO_EMPTY);
463 $server_sort_array = $thread_list;
464
465 $indent_array = get_parent_level ($thread_new);
466 sqsession_register($indent_array, 'indent_array');
467
468 sqsession_register($server_sort_array, 'server_sort_array');
469 return $thread_list;
470 }
471
472
473 function elapsedTime($start) {
474 $stop = gettimeofday();
475 $timepassed = 1000000 * ($stop['sec'] - $start['sec']) + $stop['usec'] - $start['usec'];
476 return $timepassed;
477 }
478
479 // only used in sqimap_get_small_header_list
480 function parseString($read,&$i) {
481 $char = $read{$i};
482 $s = '';
483 if ($char == '"') {
484 $iPos = ++$i;
485 while (true) {
486 $iPos = strpos($read,'"',$iPos);
487 if (!$iPos) break;
488 if ($iPos && $read{$iPos -1} != '\\') {
489 $s = substr($read,$i,($iPos-$i));
490 $i = $iPos;
491 break;
492 }
493 $iPos++;
494 if ($iPos > strlen($read)) {
495 break;
496 }
497 }
498 } else if ($char == '{') {
499 $lit_cnt = '';
500 ++$i;
501 $iPos = strpos($read,'}',$i);
502 if ($iPos) {
503 $lit_cnt = substr($read, $i, $iPos - $i);
504 $i += strlen($lit_cnt) + 3; /* skip } + \r + \n */
505 /* Now read the literal */
506 $s = ($lit_cnt ? substr($read,$i,$lit_cnt): '');
507 $i += $lit_cnt;
508 /* temp bugfix (SM 1.5 will have a working clean version)
509 too much work to implement that version right now */
510 --$i;
511 } else { /* should never happen */
512 $i += 3; /* } + \r + \n */
513 $s = '';
514 }
515 } else {
516 return false;
517 }
518 ++$i;
519 return $s;
520 }
521
522 // only used in sqimap_get_small_header_list
523 function parseArray($read,&$i) {
524 $i = strpos($read,'(',$i);
525 $i_pos = strpos($read,')',$i);
526 $s = substr($read,$i+1,$i_pos - $i -1);
527 $a = explode(' ',$s);
528 if ($i_pos) {
529 $i = $i_pos+1;
530 return $a;
531 } else {
532 return false;
533 }
534 }
535
536 function sqimap_get_small_header_list ($imap_stream, $msg_list, $show_num=false,
537 $aHeaderFields = array('Date', 'To', 'Cc', 'From', 'Subject', 'X-Priority', 'Content-Type'),
538 $aFetchItems = array('FLAGS', 'UID', 'RFC822.SIZE', 'INTERNALDATE')) {
539
540 global $squirrelmail_language, $color, $data_dir, $username, $imap_server_type;
541 global $allow_server_sort;
542
543 $messages = array();
544 $read_list = array();
545
546 /* Get the small headers for each message in $msg_list */
547 if ($show_num != '999999' && $show_num != '*' ) {
548 $msgs_str = sqimap_message_list_squisher($msg_list);
549 /*
550 * We need to return the data in the same order as the caller supplied
551 * in $msg_list, but IMAP servers are free to return responses in
552 * whatever order they wish... So we need to re-sort manually
553 */
554 for ($i = 0; $i < sizeof($msg_list); $i++) {
555 $messages["$msg_list[$i]"] = array();
556 }
557 } else {
558 $msgs_str = '1:*';
559 }
560
561
562
563 /*
564 * Create the query
565 */
566
567 $internaldate = getPref($data_dir, $username, 'internal_date_sort');
568 if (($i = array_search('INTERNALDATE',$aFetchItems,true)) !== false && $internaldate == false) {
569 unset($aFetchItems[$i]);
570 }
571 $sFetchItems = '';
572 $query = "FETCH $msgs_str (";
573 if (count($aFetchItems)) {
574 $sFetchItems = implode(' ',$aFetchItems);
575 }
576 if (count($aHeaderFields)) {
577 $sHeaderFields = implode(' ',$aHeaderFields);
578 $sFetchItems .= ' BODY.PEEK[HEADER.FIELDS ('.$sHeaderFields.')]';
579 }
580 $query .= trim($sFetchItems) . ')';
581 $read_list = sqimap_run_command_list ($imap_stream, $query, true, $response, $message, TRUE);
582 $i = 0;
583
584 foreach ($read_list as $r) {
585 // use unset because we do isset below
586 $read = implode('',$r);
587
588 /*
589 * #id<space>FETCH<space>(
590 */
591
592 /* extract the message id */
593 $i_space = strpos($read,' ',2);
594 $id = substr($read,2,$i_space-2);
595 $fetch = substr($read,$i_space+1,5);
596 if (!is_numeric($id) && $fetch !== 'FETCH') {
597 set_up_language($squirrelmail_language);
598 echo '<br><b><font color=$color[2]>' .
599 _("ERROR : Could not complete request.") .
600 '</b><br>' .
601 _("Unknown response from IMAP server: ") . ' 1.' .
602 htmlspecialchars($read) . "</font><br>\n";
603 break;
604 }
605 $i = strpos($read,'(',$i_space+5);
606 $read = substr($read,$i+1);
607 $i_len = strlen($read);
608 $i = 0;
609 while ($i < $i_len && $i !== false) {
610 /* get argument */
611 $read = trim(substr($read,$i));
612 $i_len = strlen($read);
613 $i = strpos($read,' ');
614 $arg = substr($read,0,$i);
615 ++$i;
616 switch ($arg)
617 {
618 case 'UID':
619 $i_pos = strpos($read,' ',$i);
620 if (!$i_pos) {
621 $i_pos = strpos($read,')',$i);
622 }
623 if ($i_pos) {
624 $unique_id = substr($read,$i,$i_pos-$i);
625 $i = $i_pos+1;
626 } else {
627 break 3;
628 }
629 break;
630 case 'FLAGS':
631 $flags = parseArray($read,$i);
632 if (!$flags) break 3;
633 $aFlags = array();
634 foreach ($flags as $flag) {
635 $flag = strtolower($flag);
636 $aFlags[$flag] = true;
637 }
638 $msg['FLAGS'] = $aFlags;
639 break;
640 case 'RFC822.SIZE':
641 $i_pos = strpos($read,' ',$i);
642 if (!$i_pos) {
643 $i_pos = strpos($read,')',$i);
644 }
645 if ($i_pos) {
646 $msg['SIZE'] = substr($read,$i,$i_pos-$i);
647 $i = $i_pos+1;
648 } else {
649 break 3;
650 }
651
652 break;
653 case 'INTERNALDATE':
654 $msg['INTERNALDATE'] = parseString($read,$i);
655 break;
656 case 'BODY.PEEK[HEADER.FIELDS':
657 case 'BODY[HEADER.FIELDS':
658 $i = strpos($read,'{',$i);
659 $header = parseString($read,$i);
660 if ($header === false) break 2;
661 /* First we replace all \r\n by \n, and unfold the header */
662 $hdr = trim(str_replace(array("\r\n", "\n\t", "\n "),array("\n", ' ', ' '), $header));
663 /* Now we can make a new header array with */
664 /* each element representing a headerline */
665 $hdr = explode("\n" , $hdr);
666 foreach ($hdr as $line) {
667 $pos = strpos($line, ':');
668 if ($pos > 0) {
669 $field = strtolower(substr($line, 0, $pos));
670 if (!strstr($field,' ')) { /* valid field */
671 $value = trim(substr($line, $pos+1));
672 switch($field)
673 {
674 case 'to': $msg['TO'] = $value; break;
675 case 'cc': $msg['CC'] = $value; break;
676 case 'from': $msg['FROM'] = $value; break;
677 case 'date':
678 $msg['DATE'] = str_replace(' ', ' ', $value);
679 break;
680 case 'x-priority': $msg['PRIORITY'] = $value; break;
681 case 'subject': $msg['SUBJECT'] = $value; break;
682 case 'content-type':
683 $type = $value;
684 if ($pos = strpos($type, ";")) {
685 $type = substr($type, 0, $pos);
686 }
687 $type = explode("/", $type);
688 if(!is_array($type)) {
689 $msg['TYPE0'] = 'text';
690 $msg['TYPE1'] = 'plain';
691 }
692 break;
693 default: break;
694 }
695 }
696 }
697 }
698 break;
699 default:
700 ++$i;
701 break;
702 }
703 }
704 $msgi ="$unique_id";
705 $msg['ID'] = $unique_id;
706
707 $messages[$msgi] = $msg;
708 ++$msgi;
709 }
710 array_reverse($messages);
711 return $messages;
712 }
713
714 /**
715 * Returns a message array with all the information about a message.
716 * See the documentation folder for more information about this array.
717 */
718 function sqimap_get_message ($imap_stream, $id, $mailbox) {
719 // typecast to int to prohibit 1:* msgs sets
720 $id = (int) $id;
721 $flags = array();
722 $read = sqimap_run_command ($imap_stream, "FETCH $id (FLAGS BODYSTRUCTURE)", true, $response, $message, TRUE);
723 if ($read) {
724 if (preg_match('/.+FLAGS\s\((.*)\)\s/AUi',$read[0],$regs)) {
725 if (trim($regs[1])) {
726 $flags = preg_split('/ /', $regs[1],-1,'PREG_SPLIT_NI_EMPTY');
727 }
728 }
729 } else {
730 /* the message was not found, maybe the mailbox was modified? */
731 global $sort, $startMessage, $color;
732
733 $errmessage = _("The server couldn't find the message you requested.") .
734 '<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).");
735 /* this will include a link back to the message list */
736 error_message($errmessage, $mailbox, $sort, (int) $startMessage, $color);
737 exit;
738 }
739 $bodystructure = implode('',$read);
740 $msg = mime_structure($bodystructure,$flags);
741 $read = sqimap_run_command ($imap_stream, "FETCH $id BODY[HEADER]", true, $response, $message, TRUE);
742 $rfc822_header = new Rfc822Header();
743 $rfc822_header->parseHeader($read);
744 $msg->rfc822_header = $rfc822_header;
745 return $msg;
746 }
747
748 ?>