imap_messages.php 34 KB

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