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