imap_messages.php 35 KB

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