imap_messages.php 38 KB

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