imap_messages.php 36 KB

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