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