imap_messages.php 34 KB

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