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