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