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