imap_messages.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  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. $sThreadResponse = '';
  311. if (isset($sRead[0])) {
  312. for ($i=0,$iCnt=count($sRead);$i<$iCnt;++$i) {
  313. if (preg_match("/^\* THREAD (.+)$/", $sRead[$i], $aMatch)) {
  314. $sThreadResponse = trim($aMatch[1]);
  315. break;
  316. }
  317. }
  318. }
  319. unset($sRead);
  320. if ($response !== 'OK') {
  321. return false;
  322. }
  323. /* Example response
  324. * S: * THREAD (2)(3 6 (4 23)(44 7 96))
  325. * -- 2
  326. *
  327. * -- 3
  328. * \-- 6
  329. * |-- 4
  330. * | \-- 23
  331. * |
  332. * \-- 44
  333. * \-- 7
  334. * \-- 96
  335. */
  336. /*
  337. * Notes for future work:
  338. * indent_array should contain: indent_level, parent and flags,
  339. * sibling nodes ..
  340. * To achieve that we need to define the following flags:
  341. * 0: hasnochildren
  342. * 1: haschildren
  343. * 2: is first
  344. * 4: is last
  345. * a node has sibling nodes if it's not the last node
  346. * a node has no sibling nodes if it's the last node
  347. * By using binary comparations we can store the flag in one var
  348. *
  349. * example:
  350. * -1 par = 0, level = 0, flag = 1 + 2 + 4 = 7 (haschildren, isfirst, islast)
  351. * \-2 par = 1, level = 1, flag = 0 + 2 = 2 (hasnochildren, isfirst)
  352. * |-3 par = 1, level = 1, flag = 1 + 4 = 5 (haschildren, islast)
  353. * \-4 par = 3, level = 2, flag = 1 + 2 + 4 = 7 (haschildren, isfirst, islast)
  354. * \-5 par = 4, level = 3, flag = 0 + 2 + 4 = 6 (hasnochildren, isfirst, islast)
  355. */
  356. $j = 0;
  357. $k = 0;
  358. $l = 0;
  359. $aUidThread = array();
  360. $aIndent = array();
  361. $aUidSubThread = array();
  362. $aDepthStack = array();
  363. $sUid = '';
  364. if ($sThreadResponse) {
  365. for ($i=0,$iCnt = strlen($sThreadResponse);$i<$iCnt;++$i) {
  366. $cChar = $sThreadResponse{$i};
  367. switch ($cChar) {
  368. case '(': // new sub thread
  369. // correction for a subthread of a thread with no parents in thread
  370. if (!count($aUidSubThread) && $j > 0) {
  371. --$l;
  372. }
  373. $aDepthStack[$j] = $l;
  374. ++$j;
  375. break;
  376. case ')': // close sub thread
  377. if($sUid !== '') {
  378. $aUidSubThread[] = $sUid;
  379. $aIndent[$sUid] = $j + $l - 1;
  380. ++$l;
  381. $sUid = '';
  382. }
  383. --$j;
  384. if ($j === 0) {
  385. // show message that starts the thread first.
  386. $aUidSubThread = array_reverse($aUidSubThread);
  387. // do not use array_merge because it's extremely slow and is causing timeouts
  388. foreach ($aUidSubThread as $iUid) {
  389. $aUidThread[] = $iUid;
  390. }
  391. $aUidSubThread = array();
  392. $l = 0;
  393. $aDepthStack = array();
  394. } else {
  395. $l = $aDepthStack[$j];
  396. }
  397. break;
  398. case ' ': // new child
  399. if ($sUid !== '') {
  400. $aUidSubThread[] = $sUid;
  401. $aIndent[$sUid] = $j + $l - 1;
  402. ++$l;
  403. $sUid = '';
  404. }
  405. break;
  406. default: // part of UID
  407. $sUid .= $cChar;
  408. break;
  409. }
  410. }
  411. }
  412. unset($sThreadResponse);
  413. // show newest threads first
  414. $aUidThread = array_reverse($aUidThread);
  415. return array($aUidThread,$aIndent);
  416. }
  417. function elapsedTime($start) {
  418. $stop = gettimeofday();
  419. $timepassed = 1000000 * ($stop['sec'] - $start['sec']) + $stop['usec'] - $start['usec'];
  420. return $timepassed;
  421. }
  422. /**
  423. * Parses a string in an imap response. String starts with " or { which means it
  424. * can handle double quoted strings and literal strings
  425. *
  426. * @param string $read imap response
  427. * @param integer $i (reference) offset in string
  428. * @return string $s parsed string without the double quotes or literal count
  429. */
  430. function parseString($read,&$i) {
  431. $char = $read{$i};
  432. $s = '';
  433. if ($char == '"') {
  434. $iPos = ++$i;
  435. while (true) {
  436. $iPos = strpos($read,'"',$iPos);
  437. if (!$iPos) break;
  438. if ($iPos && $read{$iPos -1} != '\\') {
  439. $s = substr($read,$i,($iPos-$i));
  440. $i = $iPos;
  441. break;
  442. }
  443. $iPos++;
  444. if ($iPos > strlen($read)) {
  445. break;
  446. }
  447. }
  448. } else if ($char == '{') {
  449. $lit_cnt = '';
  450. ++$i;
  451. $iPos = strpos($read,'}',$i);
  452. if ($iPos) {
  453. $lit_cnt = substr($read, $i, $iPos - $i);
  454. $i += strlen($lit_cnt) + 3; /* skip } + \r + \n */
  455. /* Now read the literal */
  456. $s = ($lit_cnt ? substr($read,$i,$lit_cnt): '');
  457. $i += $lit_cnt;
  458. /* temp bugfix (SM 1.5 will have a working clean version)
  459. too much work to implement that version right now */
  460. --$i;
  461. } else { /* should never happen */
  462. $i += 3; /* } + \r + \n */
  463. $s = '';
  464. }
  465. } else {
  466. return false;
  467. }
  468. ++$i;
  469. return $s;
  470. }
  471. /**
  472. * Parses a string containing an array from an imap response. String starts with ( and end with )
  473. *
  474. * @param string $read imap response
  475. * @param integer $i (reference) offset in string
  476. * @return array $a
  477. */
  478. function parseArray($read,&$i) {
  479. $i = strpos($read,'(',$i);
  480. $i_pos = strpos($read,')',$i);
  481. $s = substr($read,$i+1,$i_pos - $i -1);
  482. $a = explode(' ',$s);
  483. if ($i_pos) {
  484. $i = $i_pos+1;
  485. return $a;
  486. } else {
  487. return false;
  488. }
  489. }
  490. /**
  491. * Retrieves a list with headers, flags, size or internaldate from the imap server
  492. *
  493. * WARNING: function is not portable between SquirrelMail 1.2.x, 1.4.x and 1.5.x.
  494. * Output format, third argument and $msg_list array format requirements differ.
  495. * @param stream $imap_stream imap connection
  496. * @param array $msg_list array with id's to create a msgs set from
  497. * @param array $aHeaderFields (since 1.5.0) requested header fields
  498. * @param array $aFetchItems (since 1.5.0) requested other fetch items like FLAGS, RFC822.SIZE
  499. * @return array $aMessages associative array with messages. Key is the UID, value is an associative array
  500. * @since 1.1.3
  501. */
  502. function sqimap_get_small_header_list($imap_stream, $msg_list,
  503. $aHeaderFields = array('Date', 'To', 'Cc', 'From', 'Subject', 'X-Priority', 'Content-Type'),
  504. $aFetchItems = array('FLAGS', 'RFC822.SIZE', 'INTERNALDATE')) {
  505. $aMessageList = array();
  506. /**
  507. * Catch other priority headers as well
  508. */
  509. if (in_array('X-Priority',$aHeaderFields,true)) {
  510. $aHeaderFields[] = 'Importance';
  511. $aHeaderFields[] = 'Priority';
  512. }
  513. $bUidFetch = ! in_array('UID', $aFetchItems, true);
  514. /* Get the small headers for each message in $msg_list */
  515. if ($msg_list !== NULL) {
  516. $msgs_str = sqimap_message_list_squisher($msg_list);
  517. /*
  518. * We need to return the data in the same order as the caller supplied
  519. * in $msg_list, but IMAP servers are free to return responses in
  520. * whatever order they wish... So we need to re-sort manually
  521. */
  522. if ($bUidFetch) {
  523. for ($i = 0; $i < sizeof($msg_list); $i++) {
  524. $aMessageList["$msg_list[$i]"] = array();
  525. }
  526. }
  527. } else {
  528. $msgs_str = '1:*';
  529. }
  530. /*
  531. * Create the query
  532. */
  533. $sFetchItems = '';
  534. $query = "FETCH $msgs_str (";
  535. if (count($aFetchItems)) {
  536. $sFetchItems = implode(' ',$aFetchItems);
  537. }
  538. if (count($aHeaderFields)) {
  539. $sHeaderFields = implode(' ',$aHeaderFields);
  540. $sFetchItems .= ' BODY.PEEK[HEADER.FIELDS ('.$sHeaderFields.')]';
  541. }
  542. $query .= trim($sFetchItems) . ')';
  543. $aResponse = sqimap_run_command_list ($imap_stream, $query, true, $response, $message, $bUidFetch);
  544. $aMessages = parseFetch($aResponse,$aMessageList);
  545. array_reverse($aMessages);
  546. return $aMessages;
  547. }
  548. /**
  549. * Parses a fetch response, currently it can hande FLAGS, HEADERS, RFC822.SIZE, INTERNALDATE and UID
  550. * @param array $aResponse Imap response
  551. * @param array $aMessageList Placeholder array for results. The keys of the
  552. * placeholder array should be the UID so we can reconstruct the order.
  553. * @return array $aMessageList associative array with messages. Key is the UID, value is an associative array
  554. * @author Marc Groot Koerkamp
  555. */
  556. function parseFetch(&$aResponse,$aMessageList = array()) {
  557. for ($j=0,$iCnt=count($aResponse);$j<$iCnt;++$j) {
  558. $aMsg = array();
  559. $read = implode('',$aResponse[$j]);
  560. // free up memmory
  561. unset($aResponse[$j]); /* unset does not reindex the array. the for loop is safe */
  562. /*
  563. * #id<space>FETCH<space>(
  564. */
  565. /* extract the message id */
  566. $i_space = strpos($read,' ',2);/* position 2ed <space> */
  567. $id = substr($read,2/* skip "*<space>" */,$i_space -2);
  568. $aMsg['ID'] = $id;
  569. $fetch = substr($read,$i_space+1,5);
  570. if (!is_numeric($id) && $fetch !== 'FETCH') {
  571. $aMsg['ERROR'] = $read; // htmlspecialchars should be done just before display. this is backend code
  572. break;
  573. }
  574. $i = strpos($read,'(',$i_space+5);
  575. $read = substr($read,$i+1);
  576. $i_len = strlen($read);
  577. $i = 0;
  578. while ($i < $i_len && $i !== false) {
  579. /* get argument */
  580. $read = trim(substr($read,$i));
  581. $i_len = strlen($read);
  582. $i = strpos($read,' ');
  583. $arg = substr($read,0,$i);
  584. ++$i;
  585. /*
  586. * use allcaps for imap items and lowcaps for headers as key for the $aMsg array
  587. */
  588. switch ($arg)
  589. {
  590. case 'UID':
  591. $i_pos = strpos($read,' ',$i);
  592. if (!$i_pos) {
  593. $i_pos = strpos($read,')',$i);
  594. }
  595. if ($i_pos) {
  596. $unique_id = substr($read,$i,$i_pos-$i);
  597. $i = $i_pos+1;
  598. } else {
  599. break 3;
  600. }
  601. break;
  602. case 'FLAGS':
  603. $flags = parseArray($read,$i);
  604. if (!$flags) break 3;
  605. $aFlags = array();
  606. foreach ($flags as $flag) {
  607. $flag = strtolower($flag);
  608. $aFlags[$flag] = true;
  609. }
  610. $aMsg['FLAGS'] = $aFlags;
  611. break;
  612. case 'RFC822.SIZE':
  613. $i_pos = strpos($read,' ',$i);
  614. if (!$i_pos) {
  615. $i_pos = strpos($read,')',$i);
  616. }
  617. if ($i_pos) {
  618. $aMsg['SIZE'] = substr($read,$i,$i_pos-$i);
  619. $i = $i_pos+1;
  620. } else {
  621. break 3;
  622. }
  623. break;
  624. case 'ENVELOPE':
  625. // sqimap_parse_address($read,$i,$aMsg);
  626. break; // to be implemented, moving imap code out of the Message class
  627. case 'BODYSTRUCTURE':
  628. break; // to be implemented, moving imap code out of the Message class
  629. case 'INTERNALDATE':
  630. $aMsg['INTERNALDATE'] = trim(str_replace(' ', ' ',parseString($read,$i)));
  631. break;
  632. case 'BODY.PEEK[HEADER.FIELDS':
  633. case 'BODY[HEADER.FIELDS':
  634. $i = strpos($read,'{',$i); // header is always returned as literal because it contain \n characters
  635. $header = parseString($read,$i);
  636. if ($header === false) break 2;
  637. /* First we replace all \r\n by \n, and unfold the header */
  638. $hdr = trim(str_replace(array("\r\n", "\n\t", "\n "),array("\n", ' ', ' '), $header));
  639. /* Now we can make a new header array with
  640. each element representing a headerline */
  641. $aHdr = explode("\n" , $hdr);
  642. $aReceived = array();
  643. foreach ($aHdr as $line) {
  644. $pos = strpos($line, ':');
  645. if ($pos > 0) {
  646. $field = strtolower(substr($line, 0, $pos));
  647. if (!strstr($field,' ')) { /* valid field */
  648. $value = trim(substr($line, $pos+1));
  649. switch($field) {
  650. case 'date':
  651. $aMsg['date'] = trim(str_replace(' ', ' ', $value));
  652. break;
  653. case 'x-priority': $aMsg['x-priority'] = ($value) ? (int) $value{0} : 3; break;
  654. case 'priority':
  655. case 'importance':
  656. // duplicate code with Rfc822Header.cls:parsePriority()
  657. if (!isset($aMsg['x-priority'])) {
  658. $aPrio = preg_split('/\s/',trim($value));
  659. $sPrio = strtolower(array_shift($aPrio));
  660. if (is_numeric($sPrio)) {
  661. $iPrio = (int) $sPrio;
  662. } elseif ( $sPrio == 'non-urgent' || $sPrio == 'low' ) {
  663. $iPrio = 3;
  664. } elseif ( $sPrio == 'urgent' || $sPrio == 'high' ) {
  665. $iPrio = 1;
  666. } else {
  667. // default is normal priority
  668. $iPrio = 3;
  669. }
  670. $aMsg['x-priority'] = $iPrio;
  671. }
  672. break;
  673. case 'content-type':
  674. $type = $value;
  675. if ($pos = strpos($type, ";")) {
  676. $type = substr($type, 0, $pos);
  677. }
  678. $type = explode("/", $type);
  679. if(!is_array($type) || count($type) < 2) {
  680. $aMsg['content-type'] = array('text','plain');
  681. } else {
  682. $aMsg['content-type'] = array(strtolower($type[0]),strtolower($type[1]));
  683. }
  684. break;
  685. case 'received':
  686. $aMsg['received'][] = $value;
  687. break;
  688. default:
  689. $aMsg[$field] = $value;
  690. break;
  691. }
  692. }
  693. }
  694. }
  695. break;
  696. default:
  697. ++$i;
  698. break;
  699. }
  700. }
  701. if (!empty($unique_id)) {
  702. $msgi = "$unique_id";
  703. $aMsg['UID'] = $unique_id;
  704. } else {
  705. $msgi = '';
  706. }
  707. $aMessageList[$msgi] = $aMsg;
  708. $aResponse[$j] = NULL;
  709. }
  710. return $aMessageList;
  711. }
  712. /**
  713. * Work in process
  714. * @private
  715. * @author Marc Groot Koerkamp
  716. */
  717. function sqimap_parse_envelope($read, &$i, &$msg) {
  718. $arg_no = 0;
  719. $arg_a = array();
  720. ++$i;
  721. for ($cnt = strlen($read); ($i < $cnt) && ($read{$i} != ')'); ++$i) {
  722. $char = strtoupper($read{$i});
  723. switch ($char) {
  724. case '{':
  725. case '"':
  726. $arg_a[] = parseString($read,$i);
  727. ++$arg_no;
  728. break;
  729. case 'N':
  730. /* probably NIL argument */
  731. if (strtoupper(substr($read, $i, 3)) == 'NIL') {
  732. $arg_a[] = '';
  733. ++$arg_no;
  734. $i += 2;
  735. }
  736. break;
  737. case '(':
  738. /* Address structure (with group support)
  739. * Note: Group support is useless on SMTP connections
  740. * because the protocol doesn't support it
  741. */
  742. $addr_a = array();
  743. $group = '';
  744. $a=0;
  745. for (; $i < $cnt && $read{$i} != ')'; ++$i) {
  746. if ($read{$i} == '(') {
  747. $addr = sqimap_parse_address($read, $i);
  748. if (($addr[3] == '') && ($addr[2] != '')) {
  749. /* start of group */
  750. $group = $addr[2];
  751. $group_addr = $addr;
  752. $j = $a;
  753. } else if ($group && ($addr[3] == '') && ($addr[2] == '')) {
  754. /* end group */
  755. if ($a == ($j+1)) { /* no group members */
  756. $group_addr[4] = $group;
  757. $group_addr[2] = '';
  758. $group_addr[0] = "$group: Undisclosed recipients;";
  759. $addr_a[] = $group_addr;
  760. $group ='';
  761. }
  762. } else {
  763. $addr[4] = $group;
  764. $addr_a[] = $addr;
  765. }
  766. ++$a;
  767. }
  768. }
  769. $arg_a[] = $addr_a;
  770. break;
  771. default: break;
  772. }
  773. }
  774. if (count($arg_a) > 9) {
  775. $d = strtr($arg_a[0], array(' ' => ' '));
  776. $d = explode(' ', $d);
  777. if (!$arg_a[1]) $arg_a[1] = '';
  778. $msg['DATE'] = $d; /* argument 1: date */
  779. $msg['SUBJECT'] = $arg_a[1]; /* argument 2: subject */
  780. $msg['FROM'] = is_array($arg_a[2]) ? $arg_a[2][0] : ''; /* argument 3: from */
  781. $msg['SENDER'] = is_array($arg_a[3]) ? $arg_a[3][0] : ''; /* argument 4: sender */
  782. $msg['REPLY-TO'] = is_array($arg_a[4]) ? $arg_a[4][0] : ''; /* argument 5: reply-to */
  783. $msg['TO'] = $arg_a[5]; /* argument 6: to */
  784. $msg['CC'] = $arg_a[6]; /* argument 7: cc */
  785. $msg['BCC'] = $arg_a[7]; /* argument 8: bcc */
  786. $msg['IN-REPLY-TO'] = $arg_a[8]; /* argument 9: in-reply-to */
  787. $msg['MESSAGE-ID'] = $arg_a[9]; /* argument 10: message-id */
  788. }
  789. }
  790. /**
  791. * Work in process
  792. * @private
  793. * @author Marc Groot Koerkamp
  794. */
  795. function sqimap_parse_address($read, &$i) {
  796. $arg_a = array();
  797. for (; $read{$i} != ')'; ++$i) {
  798. $char = strtoupper($read{$i});
  799. switch ($char) {
  800. case '{':
  801. case '"': $arg_a[] = parseString($read,$i); break;
  802. case 'n':
  803. case 'N':
  804. if (strtoupper(substr($read, $i, 3)) == 'NIL') {
  805. $arg_a[] = '';
  806. $i += 2;
  807. }
  808. break;
  809. default: break;
  810. }
  811. }
  812. if (count($arg_a) == 4) {
  813. return $arg_a;
  814. // $adr = new AddressStructure();
  815. // $adr->personal = $arg_a[0];
  816. // $adr->adl = $arg_a[1];
  817. // $adr->mailbox = $arg_a[2];
  818. // $adr->host = $arg_a[3];
  819. } else {
  820. $adr = '';
  821. }
  822. return $adr;
  823. }
  824. /**
  825. * Returns a message array with all the information about a message.
  826. * See the documentation folder for more information about this array.
  827. *
  828. * @param resource $imap_stream imap connection
  829. * @param integer $id uid of the message
  830. * @param string $mailbox used for error handling, can be removed because we should return an error code and generate the message elsewhere
  831. * @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)
  832. * @return mixed Message object or FALSE/error string if error occurred and $hide is set to 2/3
  833. */
  834. function sqimap_get_message($imap_stream, $id, $mailbox, $hide=0) {
  835. // typecast to int to prohibit 1:* msgs sets
  836. $id = (int) $id;
  837. $flags = array();
  838. $read = sqimap_run_command($imap_stream, "FETCH $id (FLAGS BODYSTRUCTURE)", true, $response, $message, TRUE);
  839. if ($read) {
  840. if (preg_match('/.+FLAGS\s\((.*)\)\s/AUi',$read[0],$regs)) {
  841. if (trim($regs[1])) {
  842. $flags = preg_split('/ /', $regs[1],-1,PREG_SPLIT_NO_EMPTY);
  843. }
  844. }
  845. } else {
  846. if ($hide == 1) exit;
  847. if ($hide == 2) return FALSE;
  848. /* the message was not found, maybe the mailbox was modified? */
  849. global $sort, $startMessage;
  850. $errmessage = _("The server couldn't find the message you requested.");
  851. if ($hide == 3) return $errmessage;
  852. $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).");
  853. /* this will include a link back to the message list */
  854. error_message($errmessage, $mailbox, $sort, (int) $startMessage);
  855. exit;
  856. }
  857. $bodystructure = implode('',$read);
  858. $msg = mime_structure($bodystructure,$flags);
  859. $read = sqimap_run_command($imap_stream, "FETCH $id BODY[HEADER]", true, $response, $message, TRUE);
  860. $rfc822_header = new Rfc822Header();
  861. $rfc822_header->parseHeader($read);
  862. $msg->rfc822_header = $rfc822_header;
  863. return $msg;
  864. }