imap_messages.php 36 KB

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