imap_messages.php 34 KB

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