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