imap_messages.php 34 KB

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