imap_messages.php 37 KB

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