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