imap_messages.php 35 KB

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