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