imap_messages.php 34 KB

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