imap_messages.php 39 KB

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