imap_messages.php 36 KB

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