imap_messages.php 30 KB

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