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