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