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