imap_messages.php 39 KB

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