imap_messages.php 36 KB

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