imap_messages.php 39 KB

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