imap_messages.php 35 KB

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