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