imap_messages.php 31 KB

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