The old thread code caused time outs with a message set of 15000 messages so
[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,'character') !== 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 * Returns an array with each element as a string representing one
302 * message-thread as returned by the IMAP server.
303 * @param resource $imap_stream IMAP socket connection
304 * @param string $search optional search string
305 * @return array
306 * @link http://www.ietf.org/internet-drafts/draft-ietf-imapext-sort-13.txt
307 */
308 function get_thread_sort($imap_stream, $search='ALL') {
309 global $sort_by_ref, $default_charset;
310
311 if ($sort_by_ref == 1) {
312 $sort_type = 'REFERENCES';
313 } else {
314 $sort_type = 'ORDEREDSUBJECT';
315 }
316 $query = "THREAD $sort_type ".strtoupper($default_charset)." $search";
317
318 // TODO use sqimap_run_command_list as we do in get_server_sort()
319 $sRead = sqimap_run_command ($imap_stream, $query, false, $response, $message, TRUE);
320
321 /* fallback to default charset */
322 if ($response == 'NO') {
323 if (strpos($message,'BADCHARSET') !== false ||
324 strpos($message,'character') !== false) {
325 sqm_trigger_imap_error('SQM_IMAP_BADCHARSET',$query, $response, $message);
326 $query = "THREAD $sort_type US-ASCII $search";
327 $sRead = sqimap_run_command ($imap_stream, $query, true, $response, $message, TRUE);
328 } else {
329 sqm_trigger_imap_error('SQM_IMAP_ERROR',$query, $response, $message);
330 }
331 } elseif ($response == 'BAD') {
332 sqm_trigger_imap_error('SQM_IMAP_NO_THREAD',$query, $response, $message);
333 }
334 if (isset($sRead[0])) {
335 for ($i=0,$iCnt=count($sRead);$i<$iCnt;++$i) {
336 if (preg_match("/^\* THREAD (.+)$/", $sRead[$i], $aMatch)) {
337 $sThreadResponse = trim($aMatch[1]);
338 break;
339 }
340 }
341 } else {
342 $sThreadResponse = "";
343 }
344 unset($sRead);
345
346 if ($response !== 'OK') {
347 return false;
348 }
349
350 /* Example response
351 * S: * THREAD (2)(3 6 (4 23)(44 7 96))
352 * -- 2
353 *
354 * -- 3
355 * \-- 6
356 * |-- 4
357 * | \-- 23
358 * |
359 * \-- 44
360 * \-- 7
361 * \-- 96
362 */
363 /*
364 * Notes for future work:
365 * indent_array should contain: indent_level, parent and flags,
366 * sibling nodes ..
367 * To achieve that we need to define the following flags:
368 * 0: hasnochildren
369 * 1: haschildren
370 * 2: is first
371 * 4: is last
372 * a node has sibling nodes if it's not the last node
373 * a node has no sibling nodes if it's the last node
374 * By using binary comparations we can store the flag in one var
375 *
376 * example:
377 * -1 par = 0, level = 0, flag = 1 + 2 + 4 = 7 (haschildren, isfirst, islast)
378 * \-2 par = 1, level = 1, flag = 0 + 2 = 2 (hasnochildren, isfirst)
379 * |-3 par = 1, level = 1, flag = 1 + 4 = 5 (haschildren, islast)
380 * \-4 par = 3, level = 2, flag = 1 + 2 + 4 = 7 (haschildren, isfirst, islast)
381 * \-5 par = 4, level = 3, flag = 0 + 2 + 4 = 6 (hasnochildren, isfirst, islast)
382 */
383
384 $j = 0;
385 $k = 0;
386 $l = 0;
387 $aUidThread = array();
388 $aIndent = array();
389 $aUidSubThread = array();
390 $aDepthStack = array();
391 $sUid = '';
392
393 if ($sThreadResponse) {
394 for ($i=0,$iCnt = strlen($sThreadResponse);$i<$iCnt;++$i) {
395 $cChar = $sThreadResponse{$i};
396 switch ($cChar) {
397 case '(': // new sub thread
398 $aDepthStack[$j] = $l;
399 ++$j;
400 break;
401 case ')': // close sub thread
402 if($sUid !== '') {
403 $aUidSubThread[] = $sUid;
404 $aIndent[$sUid] = $j + $l - 1;
405 ++$l;
406 $sUid = '';
407 }
408 --$j;
409 if ($j === 0) {
410 // show message that starts the thread first.
411 $aUidSubThread = array_reverse($aUidSubThread);
412 // do not use array_merge because it's extremely slow and is causing timeouts
413 foreach ($aUidSubThread as $iUid) {
414 $aUidThread[] = $iUid;
415 }
416 $aUidSubThread = array();
417 $l = 0;
418 $aDepthStack = array();
419 } else {
420 $l = $aDepthStack[$j];
421 }
422 break;
423 case ' ': // new child
424 if ($sUid !== '') {
425 $aUidSubThread[] = $sUid;
426 $aIndent[$sUid] = $j + $l - 1;
427 ++$l;
428 $sUid = '';
429 }
430 break;
431 default: // part of UID
432 $sUid .= $cChar;
433 break;
434 }
435 }
436 }
437 unset($sThreadResponse);
438 // show newest threads first
439 $aUidThread = array_reverse($aUidThread);
440 return array($aUidThread,$aIndent);
441 }
442
443
444 function elapsedTime($start) {
445 $stop = gettimeofday();
446 $timepassed = 1000000 * ($stop['sec'] - $start['sec']) + $stop['usec'] - $start['usec'];
447 return $timepassed;
448 }
449
450
451 /**
452 * Normalise the different Priority headers into a uniform value,
453 * namely that of the X-Priority header (1, 3, 5). Supports:
454 * Prioirty, X-Priority, Importance.
455 * X-MS-Mail-Priority is not parsed because it always coincides
456 * with one of the other headers.
457 *
458 * FIXME: DUPLICATE CODE ALERT:
459 * NOTE: this is actually a duplicate from the function in
460 * class/mime/Rfc822Header.php.
461 * @todo obsolate function or use it instead of code block in parseFetch()
462 */
463 function parsePriority($sValue) {
464 $aValue = split('/\w/',trim($sValue));
465 $value = strtolower(array_shift($aValue));
466 if ( is_numeric($value) ) {
467 return $value;
468 }
469 if ( $value == 'urgent' || $value == 'high' ) {
470 return 1;
471 } elseif ( $value == 'non-urgent' || $value == 'low' ) {
472 return 5;
473 }
474 return 3;
475 }
476
477 /**
478 * Parses a string in an imap response. String starts with " or { which means it
479 * can handle double quoted strings and literal strings
480 *
481 * @param string $read imap response
482 * @param integer $i (reference) offset in string
483 * @return string $s parsed string without the double quotes or literal count
484 */
485 function parseString($read,&$i) {
486 $char = $read{$i};
487 $s = '';
488 if ($char == '"') {
489 $iPos = ++$i;
490 while (true) {
491 $iPos = strpos($read,'"',$iPos);
492 if (!$iPos) break;
493 if ($iPos && $read{$iPos -1} != '\\') {
494 $s = substr($read,$i,($iPos-$i));
495 $i = $iPos;
496 break;
497 }
498 $iPos++;
499 if ($iPos > strlen($read)) {
500 break;
501 }
502 }
503 } else if ($char == '{') {
504 $lit_cnt = '';
505 ++$i;
506 $iPos = strpos($read,'}',$i);
507 if ($iPos) {
508 $lit_cnt = substr($read, $i, $iPos - $i);
509 $i += strlen($lit_cnt) + 3; /* skip } + \r + \n */
510 /* Now read the literal */
511 $s = ($lit_cnt ? substr($read,$i,$lit_cnt): '');
512 $i += $lit_cnt;
513 /* temp bugfix (SM 1.5 will have a working clean version)
514 too much work to implement that version right now */
515 --$i;
516 } else { /* should never happen */
517 $i += 3; /* } + \r + \n */
518 $s = '';
519 }
520 } else {
521 return false;
522 }
523 ++$i;
524 return $s;
525 }
526
527
528 /**
529 * Parses a string containing an array from an imap response. String starts with ( and end with )
530 *
531 * @param string $read imap response
532 * @param integer $i (reference) offset in string
533 * @return array $a
534 */
535 function parseArray($read,&$i) {
536 $i = strpos($read,'(',$i);
537 $i_pos = strpos($read,')',$i);
538 $s = substr($read,$i+1,$i_pos - $i -1);
539 $a = explode(' ',$s);
540 if ($i_pos) {
541 $i = $i_pos+1;
542 return $a;
543 } else {
544 return false;
545 }
546 }
547
548
549 /**
550 * Retrieves a list with headers, flags, size or internaldate from the imap server
551 *
552 * WARNING: function is not portable between SquirrelMail 1.2.x, 1.4.x and 1.5.x.
553 * Output format, third argument and $msg_list array format requirements differ.
554 * @param stream $imap_stream imap connection
555 * @param array $msg_list array with id's to create a msgs set from
556 * @param array $aHeaderFields (since 1.5.0) requested header fields
557 * @param array $aFetchItems (since 1.5.0) requested other fetch items like FLAGS, RFC822.SIZE
558 * @return array $aMessages associative array with messages. Key is the UID, value is an associative array
559 * @since 1.1.3
560 */
561 function sqimap_get_small_header_list($imap_stream, $msg_list,
562 $aHeaderFields = array('Date', 'To', 'Cc', 'From', 'Subject', 'X-Priority', 'Content-Type'),
563 $aFetchItems = array('FLAGS', 'RFC822.SIZE', 'INTERNALDATE')) {
564
565 $aMessageList = array();
566
567 /**
568 * Catch other priority headers as well
569 */
570 if (in_array('X-Priority',$aHeaderFields,true)) {
571 $aHeaderFields[] = 'Importance';
572 $aHeaderFields[] = 'Priority';
573 }
574
575 $bUidFetch = ! in_array('UID', $aFetchItems, true);
576
577 /* Get the small headers for each message in $msg_list */
578 if ($msg_list !== NULL) {
579 $msgs_str = sqimap_message_list_squisher($msg_list);
580 /*
581 * We need to return the data in the same order as the caller supplied
582 * in $msg_list, but IMAP servers are free to return responses in
583 * whatever order they wish... So we need to re-sort manually
584 */
585 if ($bUidFetch) {
586 for ($i = 0; $i < sizeof($msg_list); $i++) {
587 $aMessageList["$msg_list[$i]"] = array();
588 }
589 }
590 } else {
591 $msgs_str = '1:*';
592 }
593
594 /*
595 * Create the query
596 */
597
598 $sFetchItems = '';
599 $query = "FETCH $msgs_str (";
600 if (count($aFetchItems)) {
601 $sFetchItems = implode(' ',$aFetchItems);
602 }
603 if (count($aHeaderFields)) {
604 $sHeaderFields = implode(' ',$aHeaderFields);
605 $sFetchItems .= ' BODY.PEEK[HEADER.FIELDS ('.$sHeaderFields.')]';
606 }
607 $query .= trim($sFetchItems) . ')';
608 $aResponse = sqimap_run_command_list ($imap_stream, $query, true, $response, $message, $bUidFetch);
609 $aMessages = parseFetch($aResponse,$aMessageList);
610 array_reverse($aMessages);
611 return $aMessages;
612 }
613
614
615 /**
616 * Parses a fetch response, currently it can hande FLAGS, HEADERS, RFC822.SIZE, INTERNALDATE and UID
617 * @param array $aResponse Imap response
618 * @param array $aMessageList Placeholder array for results. The keys of the
619 * placeholder array should be the UID so we can reconstruct the order.
620 * @return array $aMessageList associative array with messages. Key is the UID, value is an associative array
621 * @author Marc Groot Koerkamp
622 */
623 function parseFetch($aResponse,$aMessageList = array()) {
624 for ($j=0,$iCnt=count($aResponse);$j<$iCnt;++$j) {
625 $aMsg = array();
626
627 $read = implode('',$aResponse[$j]);
628 // free up memmory
629 unset($aResponse[$j]); /* unset does not reindex the array. the for loop is safe */
630 /*
631 * #id<space>FETCH<space>(
632 */
633
634 /* extract the message id */
635 $i_space = strpos($read,' ',2);/* position 2ed <space> */
636 $id = substr($read,2/* skip "*<space>" */,$i_space -2);
637 $aMsg['ID'] = $id;
638 $fetch = substr($read,$i_space+1,5);
639 if (!is_numeric($id) && $fetch !== 'FETCH') {
640 $aMsg['ERROR'] = $read; // htmlspecialchars should be done just before display. this is backend code
641 break;
642 }
643 $i = strpos($read,'(',$i_space+5);
644 $read = substr($read,$i+1);
645 $i_len = strlen($read);
646 $i = 0;
647 while ($i < $i_len && $i !== false) {
648 /* get argument */
649 $read = trim(substr($read,$i));
650 $i_len = strlen($read);
651 $i = strpos($read,' ');
652 $arg = substr($read,0,$i);
653 ++$i;
654 /*
655 * use allcaps for imap items and lowcaps for headers as key for the $aMsg array
656 */
657 switch ($arg)
658 {
659 case 'UID':
660 $i_pos = strpos($read,' ',$i);
661 if (!$i_pos) {
662 $i_pos = strpos($read,')',$i);
663 }
664 if ($i_pos) {
665 $unique_id = substr($read,$i,$i_pos-$i);
666 $i = $i_pos+1;
667 } else {
668 break 3;
669 }
670 break;
671 case 'FLAGS':
672 $flags = parseArray($read,$i);
673 if (!$flags) break 3;
674 $aFlags = array();
675 foreach ($flags as $flag) {
676 $flag = strtolower($flag);
677 $aFlags[$flag] = true;
678 }
679 $aMsg['FLAGS'] = $aFlags;
680 break;
681 case 'RFC822.SIZE':
682 $i_pos = strpos($read,' ',$i);
683 if (!$i_pos) {
684 $i_pos = strpos($read,')',$i);
685 }
686 if ($i_pos) {
687 $aMsg['SIZE'] = substr($read,$i,$i_pos-$i);
688 $i = $i_pos+1;
689 } else {
690 break 3;
691 }
692 break;
693 case 'ENVELOPE':
694 // sqimap_parse_address($read,$i,$aMsg);
695 break; // to be implemented, moving imap code out of the Message class
696 case 'BODYSTRUCTURE':
697 break; // to be implemented, moving imap code out of the Message class
698 case 'INTERNALDATE':
699 $aMsg['INTERNALDATE'] = trim(str_replace(' ', ' ',parseString($read,$i)));
700 break;
701 case 'BODY.PEEK[HEADER.FIELDS':
702 case 'BODY[HEADER.FIELDS':
703 $i = strpos($read,'{',$i); // header is always returned as literal because it contain \n characters
704 $header = parseString($read,$i);
705 if ($header === false) break 2;
706 /* First we replace all \r\n by \n, and unfold the header */
707 $hdr = trim(str_replace(array("\r\n", "\n\t", "\n "),array("\n", ' ', ' '), $header));
708 /* Now we can make a new header array with
709 each element representing a headerline */
710 $aHdr = explode("\n" , $hdr);
711 $aReceived = array();
712 foreach ($aHdr as $line) {
713 $pos = strpos($line, ':');
714 if ($pos > 0) {
715 $field = strtolower(substr($line, 0, $pos));
716 if (!strstr($field,' ')) { /* valid field */
717 $value = trim(substr($line, $pos+1));
718 switch($field) {
719 case 'date':
720 $aMsg['date'] = trim(str_replace(' ', ' ', $value));
721 break;
722 case 'x-priority': $aMsg['x-priority'] = ($value) ? (int) $value{0} : 3; break;
723 case 'priority':
724 case 'importance':
725 if (!isset($aMsg['x-priority'])) {
726 $aPrio = split('/\w/',trim($value));
727 $sPrio = strtolower(array_shift($aPrio));
728 if (is_numeric($sPrio)) {
729 $iPrio = (int) $sPrio;
730 } elseif ( $sPrio == 'non-urgent' || $sPrio == 'low' ) {
731 $iPrio = 3;
732 } elseif ( $sPrio == 'urgent' || $sPrio == 'high' ) {
733 $iPrio = 1;
734 } else {
735 // default is normal priority
736 $iPrio = 3;
737 }
738 $aMsg['x-priority'] = $iPrio;
739 }
740 break;
741 case 'content-type':
742 $type = $value;
743 if ($pos = strpos($type, ";")) {
744 $type = substr($type, 0, $pos);
745 }
746 $type = explode("/", $type);
747 if(!is_array($type) || count($type) < 2) {
748 $aMsg['content-type'] = array('text','plain');
749 } else {
750 $aMsg['content-type'] = array(strtolower($type[0]),strtolower($type[1]));
751 }
752 break;
753 case 'received':
754 $aMsg['received'][] = $value;
755 break;
756 default:
757 $aMsg[$field] = $value;
758 break;
759 }
760 }
761 }
762 }
763 break;
764 default:
765 ++$i;
766 break;
767 }
768 }
769 if (!empty($unique_id)) {
770 $msgi = "$unique_id";
771 $aMsg['UID'] = $unique_id;
772 } else {
773 $msgi = '';
774 }
775 $aMessageList[$msgi] = $aMsg;
776 }
777 return $aMessageList;
778 }
779
780 /**
781 * Work in process
782 * @private
783 * @author Marc Groot Koerkamp
784 */
785 function sqimap_parse_envelope($read, &$i, &$msg) {
786 $arg_no = 0;
787 $arg_a = array();
788 ++$i;
789 for ($cnt = strlen($read); ($i < $cnt) && ($read{$i} != ')'); ++$i) {
790 $char = strtoupper($read{$i});
791 switch ($char) {
792 case '{':
793 case '"':
794 $arg_a[] = parseString($read,$i);
795 ++$arg_no;
796 break;
797 case 'N':
798 /* probably NIL argument */
799 if (strtoupper(substr($read, $i, 3)) == 'NIL') {
800 $arg_a[] = '';
801 ++$arg_no;
802 $i += 2;
803 }
804 break;
805 case '(':
806 /* Address structure (with group support)
807 * Note: Group support is useless on SMTP connections
808 * because the protocol doesn't support it
809 */
810 $addr_a = array();
811 $group = '';
812 $a=0;
813 for (; $i < $cnt && $read{$i} != ')'; ++$i) {
814 if ($read{$i} == '(') {
815 $addr = sqimap_parse_address($read, $i);
816 if (($addr[3] == '') && ($addr[2] != '')) {
817 /* start of group */
818 $group = $addr[2];
819 $group_addr = $addr;
820 $j = $a;
821 } else if ($group && ($addr[3] == '') && ($addr[2] == '')) {
822 /* end group */
823 if ($a == ($j+1)) { /* no group members */
824 $group_addr[4] = $group;
825 $group_addr[2] = '';
826 $group_addr[0] = "$group: Undisclosed recipients;";
827 $addr_a[] = $group_addr;
828 $group ='';
829 }
830 } else {
831 $addr[4] = $group;
832 $addr_a[] = $addr;
833 }
834 ++$a;
835 }
836 }
837 $arg_a[] = $addr_a;
838 break;
839 default: break;
840 }
841 }
842
843 if (count($arg_a) > 9) {
844 $d = strtr($arg_a[0], array(' ' => ' '));
845 $d = explode(' ', $d);
846 if (!$arg_a[1]) $arg_a[1] = '';
847 $msg['DATE'] = $d; /* argument 1: date */
848 $msg['SUBJECT'] = $arg_a[1]; /* argument 2: subject */
849 $msg['FROM'] = is_array($arg_a[2]) ? $arg_a[2][0] : ''; /* argument 3: from */
850 $msg['SENDER'] = is_array($arg_a[3]) ? $arg_a[3][0] : ''; /* argument 4: sender */
851 $msg['REPLY-TO'] = is_array($arg_a[4]) ? $arg_a[4][0] : ''; /* argument 5: reply-to */
852 $msg['TO'] = $arg_a[5]; /* argument 6: to */
853 $msg['CC'] = $arg_a[6]; /* argument 7: cc */
854 $msg['BCC'] = $arg_a[7]; /* argument 8: bcc */
855 $msg['IN-REPLY-TO'] = $arg_a[8]; /* argument 9: in-reply-to */
856 $msg['MESSAGE-ID'] = $arg_a[9]; /* argument 10: message-id */
857 }
858 }
859
860
861 /**
862 * Work in process
863 * @private
864 * @author Marc Groot Koerkamp
865 */
866 function sqimap_parse_address($read, &$i) {
867 $arg_a = array();
868 for (; $read{$i} != ')'; ++$i) {
869 $char = strtoupper($read{$i});
870 switch ($char) {
871 case '{':
872 case '"': $arg_a[] = parseString($read,$i); break;
873 case 'n':
874 case 'N':
875 if (strtoupper(substr($read, $i, 3)) == 'NIL') {
876 $arg_a[] = '';
877 $i += 2;
878 }
879 break;
880 default: break;
881 }
882 }
883
884 if (count($arg_a) == 4) {
885 return $arg_a;
886
887 // $adr = new AddressStructure();
888 // $adr->personal = $arg_a[0];
889 // $adr->adl = $arg_a[1];
890 // $adr->mailbox = $arg_a[2];
891 // $adr->host = $arg_a[3];
892 } else {
893 $adr = '';
894 }
895 return $adr;
896 }
897
898
899 /**
900 * Returns a message array with all the information about a message.
901 * See the documentation folder for more information about this array.
902 *
903 * @param resource $imap_stream imap connection
904 * @param integer $id uid of the message
905 * @param string $mailbox used for error handling, can be removed because we should return an error code and generate the message elsewhere
906 * @return Message Message object
907 */
908 function sqimap_get_message($imap_stream, $id, $mailbox) {
909 // typecast to int to prohibit 1:* msgs sets
910 $id = (int) $id;
911 $flags = array();
912 $read = sqimap_run_command($imap_stream, "FETCH $id (FLAGS BODYSTRUCTURE)", true, $response, $message, TRUE);
913 if ($read) {
914 if (preg_match('/.+FLAGS\s\((.*)\)\s/AUi',$read[0],$regs)) {
915 if (trim($regs[1])) {
916 $flags = preg_split('/ /', $regs[1],-1,'PREG_SPLIT_NI_EMPTY');
917 }
918 }
919 } else {
920 /* the message was not found, maybe the mailbox was modified? */
921 global $sort, $startMessage, $color;
922
923 $errmessage = _("The server couldn't find the message you requested.") .
924 '<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).");
925 /* this will include a link back to the message list */
926 error_message($errmessage, $mailbox, $sort, (int) $startMessage, $color);
927 exit;
928 }
929 $bodystructure = implode('',$read);
930 $msg = mime_structure($bodystructure,$flags);
931 $read = sqimap_run_command($imap_stream, "FETCH $id BODY[HEADER]", true, $response, $message, TRUE);
932 $rfc822_header = new Rfc822Header();
933 $rfc822_header->parseHeader($read);
934 $msg->rfc822_header = $rfc822_header;
935 return $msg;
936 }
937
938 ?>