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