imap_messages.php 35 KB

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