imap_messages.php 35 KB

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