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