imap_messages.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  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. /**
  446. * Parses a string in an imap response. String starts with " or { which means it
  447. * can handle double quoted strings and literal strings
  448. *
  449. * @param string $read imap response
  450. * @param integer $i (reference) offset in string
  451. * @return string $s parsed string without the double quotes or literal count
  452. */
  453. function parseString($read,&$i) {
  454. $char = $read{$i};
  455. $s = '';
  456. if ($char == '"') {
  457. $iPos = ++$i;
  458. while (true) {
  459. $iPos = strpos($read,'"',$iPos);
  460. if (!$iPos) break;
  461. if ($iPos && $read{$iPos -1} != '\\') {
  462. $s = substr($read,$i,($iPos-$i));
  463. $i = $iPos;
  464. break;
  465. }
  466. $iPos++;
  467. if ($iPos > strlen($read)) {
  468. break;
  469. }
  470. }
  471. } else if ($char == '{') {
  472. $lit_cnt = '';
  473. ++$i;
  474. $iPos = strpos($read,'}',$i);
  475. if ($iPos) {
  476. $lit_cnt = substr($read, $i, $iPos - $i);
  477. $i += strlen($lit_cnt) + 3; /* skip } + \r + \n */
  478. /* Now read the literal */
  479. $s = ($lit_cnt ? substr($read,$i,$lit_cnt): '');
  480. $i += $lit_cnt;
  481. /* temp bugfix (SM 1.5 will have a working clean version)
  482. too much work to implement that version right now */
  483. --$i;
  484. } else { /* should never happen */
  485. $i += 3; /* } + \r + \n */
  486. $s = '';
  487. }
  488. } else {
  489. return false;
  490. }
  491. ++$i;
  492. return $s;
  493. }
  494. /**
  495. * Parses a string containing an array from an imap response. String starts with ( and end with )
  496. *
  497. * @param string $read imap response
  498. * @param integer $i (reference) offset in string
  499. * @return array $a
  500. */
  501. function parseArray($read,&$i) {
  502. $i = strpos($read,'(',$i);
  503. $i_pos = strpos($read,')',$i);
  504. $s = substr($read,$i+1,$i_pos - $i -1);
  505. $a = explode(' ',$s);
  506. if ($i_pos) {
  507. $i = $i_pos+1;
  508. return $a;
  509. } else {
  510. return false;
  511. }
  512. }
  513. /**
  514. * Retrieves a list with headers, flags, size or internaldate from the imap server
  515. * @param resource $imap_stream imap connection
  516. * @param array $msg_list array with id's to create a msgs set from
  517. * @param array $aHeaderFields requested header fields
  518. * @param array $aFetchItems requested other fetch items like FLAGS, RFC822.SIZE
  519. * @return array $aMessages associative array with messages. Key is the UID, value is an associative array
  520. */
  521. function sqimap_get_small_header_list($imap_stream, $msg_list,
  522. $aHeaderFields = array('Date', 'To', 'Cc', 'From', 'Subject', 'X-Priority', 'Content-Type'),
  523. $aFetchItems = array('FLAGS', 'RFC822.SIZE', 'INTERNALDATE')) {
  524. $aMessageList = array();
  525. $bUidFetch = ! in_array('UID', $aFetchItems, true);
  526. /* Get the small headers for each message in $msg_list */
  527. if ($msg_list !== NULL) {
  528. $msgs_str = sqimap_message_list_squisher($msg_list);
  529. /*
  530. * We need to return the data in the same order as the caller supplied
  531. * in $msg_list, but IMAP servers are free to return responses in
  532. * whatever order they wish... So we need to re-sort manually
  533. */
  534. if ($bUidFetch) {
  535. for ($i = 0; $i < sizeof($msg_list); $i++) {
  536. $aMessageList["$msg_list[$i]"] = array();
  537. }
  538. }
  539. } else {
  540. $msgs_str = '1:*';
  541. }
  542. /*
  543. * Create the query
  544. */
  545. $sFetchItems = '';
  546. $query = "FETCH $msgs_str (";
  547. if (count($aFetchItems)) {
  548. $sFetchItems = implode(' ',$aFetchItems);
  549. }
  550. if (count($aHeaderFields)) {
  551. $sHeaderFields = implode(' ',$aHeaderFields);
  552. $sFetchItems .= ' BODY.PEEK[HEADER.FIELDS ('.$sHeaderFields.')]';
  553. }
  554. $query .= trim($sFetchItems) . ')';
  555. $aResponse = sqimap_run_command_list ($imap_stream, $query, true, $response, $message, $bUidFetch);
  556. $aMessages = parseFetch($aResponse,$aMessageList);
  557. array_reverse($aMessages);
  558. return $aMessages;
  559. }
  560. /**
  561. * Parses a fetch response, currently it can hande FLAGS, HEADERS, RFC822.SIZE, INTERNALDATE and UID
  562. * @param array $aResponse Imap response
  563. * @param array $aMessageList Placeholder array for results. The keys of the
  564. * placeholder array should be the UID so we can reconstruct the order.
  565. * @return array $aMessageList associative array with messages. Key is the UID, value is an associative array
  566. * @author Marc Groot Koerkamp
  567. */
  568. function parseFetch($aResponse,$aMessageList = array()) {
  569. foreach ($aResponse as $r) {
  570. $msg = array();
  571. // use unset because we do isset below
  572. $read = implode('',$r);
  573. /*
  574. * #id<space>FETCH<space>(
  575. */
  576. /* extract the message id */
  577. $i_space = strpos($read,' ',2);
  578. $id = substr($read,2,$i_space-2);
  579. $msg['ID'] = $id;
  580. $fetch = substr($read,$i_space+1,5);
  581. if (!is_numeric($id) && $fetch !== 'FETCH') {
  582. $msg['ERROR'] = $read; // htmlspecialchars should be done just before display. this is backend code
  583. break;
  584. }
  585. $i = strpos($read,'(',$i_space+5);
  586. $read = substr($read,$i+1);
  587. $i_len = strlen($read);
  588. $i = 0;
  589. while ($i < $i_len && $i !== false) {
  590. /* get argument */
  591. $read = trim(substr($read,$i));
  592. $i_len = strlen($read);
  593. $i = strpos($read,' ');
  594. $arg = substr($read,0,$i);
  595. ++$i;
  596. switch ($arg)
  597. {
  598. case 'UID':
  599. $i_pos = strpos($read,' ',$i);
  600. if (!$i_pos) {
  601. $i_pos = strpos($read,')',$i);
  602. }
  603. if ($i_pos) {
  604. $unique_id = substr($read,$i,$i_pos-$i);
  605. $i = $i_pos+1;
  606. } else {
  607. break 3;
  608. }
  609. break;
  610. case 'FLAGS':
  611. $flags = parseArray($read,$i);
  612. if (!$flags) break 3;
  613. $aFlags = array();
  614. foreach ($flags as $flag) {
  615. $flag = strtolower($flag);
  616. $aFlags[$flag] = true;
  617. }
  618. $msg['FLAGS'] = $aFlags;
  619. break;
  620. case 'RFC822.SIZE':
  621. $i_pos = strpos($read,' ',$i);
  622. if (!$i_pos) {
  623. $i_pos = strpos($read,')',$i);
  624. }
  625. if ($i_pos) {
  626. $msg['SIZE'] = substr($read,$i,$i_pos-$i);
  627. $i = $i_pos+1;
  628. } else {
  629. break 3;
  630. }
  631. break;
  632. case 'ENVELOPE':
  633. break; // to be implemented, moving imap code out of the nessages class
  634. sqimap_parse_address($read,$i,$msg);
  635. break; // to be implemented, moving imap code out of the nessages class
  636. case 'BODYSTRUCTURE':
  637. break;
  638. case 'INTERNALDATE':
  639. $msg['INTERNALDATE'] = trim(str_replace(' ', ' ',parseString($read,$i)));
  640. break;
  641. case 'BODY.PEEK[HEADER.FIELDS':
  642. case 'BODY[HEADER.FIELDS':
  643. $i = strpos($read,'{',$i);
  644. $header = parseString($read,$i);
  645. if ($header === false) break 2;
  646. /* First we replace all \r\n by \n, and unfold the header */
  647. $hdr = trim(str_replace(array("\r\n", "\n\t", "\n "),array("\n", ' ', ' '), $header));
  648. /* Now we can make a new header array with */
  649. /* each element representing a headerline */
  650. $hdr = explode("\n" , $hdr);
  651. $aReceived = array();
  652. foreach ($hdr as $line) {
  653. $pos = strpos($line, ':');
  654. if ($pos > 0) {
  655. $field = strtolower(substr($line, 0, $pos));
  656. if (!strstr($field,' ')) { /* valid field */
  657. $value = trim(substr($line, $pos+1));
  658. switch($field)
  659. {
  660. case 'to': $msg['TO'] = $value; break;
  661. case 'cc': $msg['CC'] = $value; break;
  662. case 'from': $msg['FROM'] = $value; break;
  663. case 'date':
  664. $msg['DATE'] = str_replace(' ', ' ', $value);
  665. break;
  666. case 'x-priority': $msg['PRIORITY'] = $value; break;
  667. case 'subject': $msg['SUBJECT'] = $value; break;
  668. case 'content-type':
  669. $type = $value;
  670. if ($pos = strpos($type, ";")) {
  671. $type = substr($type, 0, $pos);
  672. }
  673. $type = explode("/", $type);
  674. if(!is_array($type) || count($type) < 2) {
  675. $msg['TYPE0'] = 'text';
  676. $msg['TYPE1'] = 'plain';
  677. } else {
  678. $msg['TYPE0'] = strtolower($type[0]);
  679. $msg['TYPE1'] = strtolower($type[1]);
  680. }
  681. break;
  682. case 'received':
  683. $aReceived[] = $value;
  684. break;
  685. default: break;
  686. }
  687. }
  688. }
  689. }
  690. if (count($aReceived)) {
  691. $msg['RECEIVED'] = $aReceived;
  692. }
  693. break;
  694. default:
  695. ++$i;
  696. break;
  697. }
  698. }
  699. $msgi ="$unique_id";
  700. $msg['UID'] = $unique_id;
  701. $aMessageList[$msgi] = $msg;
  702. ++$msgi;
  703. }
  704. return $aMessageList;
  705. }
  706. /**
  707. * Work in process
  708. * @private
  709. * @author Marc Groot Koerkamp
  710. */
  711. function sqimap_parse_envelope($read, &$i, &$msg) {
  712. $arg_no = 0;
  713. $arg_a = array();
  714. ++$i;
  715. for ($cnt = strlen($read); ($i < $cnt) && ($read{$i} != ')'); ++$i) {
  716. $char = strtoupper($read{$i});
  717. switch ($char) {
  718. case '{':
  719. case '"':
  720. $arg_a[] = parseString($read,$i);
  721. ++$arg_no;
  722. break;
  723. case 'N':
  724. /* probably NIL argument */
  725. if (strtoupper(substr($read, $i, 3)) == 'NIL') {
  726. $arg_a[] = '';
  727. ++$arg_no;
  728. $i += 2;
  729. }
  730. break;
  731. case '(':
  732. /* Address structure (with group support)
  733. * Note: Group support is useless on SMTP connections
  734. * because the protocol doesn't support it
  735. */
  736. $addr_a = array();
  737. $group = '';
  738. $a=0;
  739. for (; $i < $cnt && $read{$i} != ')'; ++$i) {
  740. if ($read{$i} == '(') {
  741. $addr = sqimap_parse_address($read, $i);
  742. if (($addr[3] == '') && ($addr[2] != '')) {
  743. /* start of group */
  744. $group = $addr[2];
  745. $group_addr = $addr;
  746. $j = $a;
  747. } else if ($group && ($addr[3] == '') && ($addr[2] == '')) {
  748. /* end group */
  749. if ($a == ($j+1)) { /* no group members */
  750. $group_addr[4] = $group;
  751. $group_addr[2] = '';
  752. $group_addr[0] = "$group: Undisclosed recipients;";
  753. $addr_a[] = $group_addr;
  754. $group ='';
  755. }
  756. } else {
  757. $addr[4] = $group;
  758. $addr_a[] = $addr;
  759. }
  760. ++$a;
  761. }
  762. }
  763. $arg_a[] = $addr_a;
  764. break;
  765. default: break;
  766. }
  767. }
  768. if (count($arg_a) > 9) {
  769. $d = strtr($arg_a[0], array(' ' => ' '));
  770. $d = explode(' ', $d);
  771. if (!$arg_a[1]) $arg_a[1] = '';
  772. $msg['DATE'] = $d; /* argument 1: date */
  773. $msg['SUBJECT'] = $arg_a[1]; /* argument 2: subject */
  774. $msg['FROM'] = is_array($arg_a[2]) ? $arg_a[2][0] : ''; /* argument 3: from */
  775. $msg['SENDER'] = is_array($arg_a[3]) ? $arg_a[3][0] : ''; /* argument 4: sender */
  776. $msg['REPLY-TO'] = is_array($arg_a[4]) ? $arg_a[4][0] : ''; /* argument 5: reply-to */
  777. $msg['TO'] = $arg_a[5]; /* argument 6: to */
  778. $msg['CC'] = $arg_a[6]; /* argument 7: cc */
  779. $msg['BCC'] = $arg_a[7]; /* argument 8: bcc */
  780. $msg['IN-REPLY-TO'] = $arg_a[8]; /* argument 9: in-reply-to */
  781. $msg['MESSAGE-ID'] = $arg_a[9]; /* argument 10: message-id */
  782. }
  783. }
  784. /**
  785. * Work in process
  786. * @private
  787. * @author Marc Groot Koerkamp
  788. */
  789. function sqimap_parse_address($read, &$i) {
  790. $arg_a = array();
  791. for (; $read{$i} != ')'; ++$i) {
  792. $char = strtoupper($read{$i});
  793. switch ($char) {
  794. case '{':
  795. case '"': $arg_a[] = parseString($read,$i); break;
  796. case 'n':
  797. case 'N':
  798. if (strtoupper(substr($read, $i, 3)) == 'NIL') {
  799. $arg_a[] = '';
  800. $i += 2;
  801. }
  802. break;
  803. default: break;
  804. }
  805. }
  806. if (count($arg_a) == 4) {
  807. return $arg_a;
  808. // $adr = new AddressStructure();
  809. // $adr->personal = $arg_a[0];
  810. // $adr->adl = $arg_a[1];
  811. // $adr->mailbox = $arg_a[2];
  812. // $adr->host = $arg_a[3];
  813. } else {
  814. $adr = '';
  815. }
  816. return $adr;
  817. }
  818. /**
  819. * Returns a message array with all the information about a message.
  820. * See the documentation folder for more information about this array.
  821. *
  822. * @param resource $imap_stream imap connection
  823. * @param integer $id uid of the message
  824. * @param string $mailbox used for error handling, can be removed because we should return an error code and generate the message elsewhere
  825. * @return Message Message object
  826. */
  827. function sqimap_get_message($imap_stream, $id, $mailbox) {
  828. // typecast to int to prohibit 1:* msgs sets
  829. $id = (int) $id;
  830. $flags = array();
  831. $read = sqimap_run_command($imap_stream, "FETCH $id (FLAGS BODYSTRUCTURE)", true, $response, $message, TRUE);
  832. if ($read) {
  833. if (preg_match('/.+FLAGS\s\((.*)\)\s/AUi',$read[0],$regs)) {
  834. if (trim($regs[1])) {
  835. $flags = preg_split('/ /', $regs[1],-1,'PREG_SPLIT_NI_EMPTY');
  836. }
  837. }
  838. } else {
  839. /* the message was not found, maybe the mailbox was modified? */
  840. global $sort, $startMessage, $color;
  841. $errmessage = _("The server couldn't find the message you requested.") .
  842. '<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).");
  843. /* this will include a link back to the message list */
  844. error_message($errmessage, $mailbox, $sort, (int) $startMessage, $color);
  845. exit;
  846. }
  847. $bodystructure = implode('',$read);
  848. $msg = mime_structure($bodystructure,$flags);
  849. $read = sqimap_run_command($imap_stream, "FETCH $id BODY[HEADER]", true, $response, $message, TRUE);
  850. $rfc822_header = new Rfc822Header();
  851. $rfc822_header->parseHeader($read);
  852. $msg->rfc822_header = $rfc822_header;
  853. return $msg;
  854. }
  855. /**
  856. * Deprecated !!!!!!! DO NOT USE THIS, use sqimap_msgs_list_copy instead
  857. */
  858. function sqimap_messages_copy($imap_stream, $start, $end, $mailbox) {
  859. $read = sqimap_run_command ($imap_stream, "COPY $start:$end " . sqimap_encode_mailbox_name($mailbox), true, $response, $message, TRUE);
  860. }
  861. /**
  862. * Deprecated !!!!!!! DO NOT USE THIS, use sqimap_msgs_list_delete instead
  863. */
  864. function sqimap_messages_delete($imap_stream, $start, $end, $mailbox, $bypass_trash=false) {
  865. global $move_to_trash, $trash_folder;
  866. if (($move_to_trash == true) && ($bypass_trash != true) &&
  867. (sqimap_mailbox_exists($imap_stream, $trash_folder) && ($mailbox != $trash_folder))) {
  868. sqimap_messages_copy ($imap_stream, $start, $end, $trash_folder);
  869. }
  870. sqimap_messages_flag ($imap_stream, $start, $end, "Deleted", true);
  871. }
  872. /**
  873. * Deprecated !!!!!!! DO NOT USE THIS, use sqimap_toggle_flag instead
  874. * Set a flag on the provided uid list
  875. * @param resource imap connection
  876. */
  877. function sqimap_messages_flag($imap_stream, $start, $end, $flag, $handle_errors) {
  878. $read = sqimap_run_command ($imap_stream, "STORE $start:$end +FLAGS (\\$flag)", $handle_errors, $response, $message, TRUE);
  879. }
  880. /**
  881. * @deprecated
  882. */
  883. function sqimap_get_small_header($imap_stream, $id, $sent) {
  884. $res = sqimap_get_small_header_list($imap_stream, $id, $sent);
  885. return $res[0];
  886. }
  887. ?>