imap_messages.php 38 KB

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