imap_messages.php 31 KB

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