imap_messages.php 34 KB

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