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