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