imap_messages.php 30 KB

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