imap_messages.php 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  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. // 1.4.x had a problem where $msg_list wasn't guaranteed to be an array,
  577. // but the following doesn't seem to be necessary in 1.5.x
  578. $msg_count = is_array($msg_list) ? sizeof($msg_list) : 1;
  579. for ($i = 0; $i < $msg_count; $i++) {
  580. $aMessageList[$msg_list[$i]] = array();
  581. }
  582. }
  583. }
  584. if (empty($msgs_str)) {
  585. $msgs_str = '1:*';
  586. }
  587. /*
  588. * Create the query
  589. */
  590. $sFetchItems = '';
  591. $query = "FETCH $msgs_str (";
  592. if (count($aFetchItems)) {
  593. $sFetchItems = implode(' ',$aFetchItems);
  594. }
  595. if (count($aHeaderFields)) {
  596. $sHeaderFields = implode(' ',$aHeaderFields);
  597. $sFetchItems .= ' BODY.PEEK[HEADER.FIELDS ('.$sHeaderFields.')]';
  598. }
  599. $query .= trim($sFetchItems) . ')';
  600. $aResponse = sqimap_run_command_list ($imap_stream, $query, true, $response, $message, $bUidFetch);
  601. $aMessages = parseFetch($aResponse,$aMessageList);
  602. array_reverse($aMessages);
  603. return $aMessages;
  604. }
  605. /**
  606. * Parses a fetch response, currently it can hande FLAGS, HEADERS, RFC822.SIZE, INTERNALDATE and UID
  607. * @param array $aResponse Imap response
  608. * @param array $aMessageList Placeholder array for results. The keys of this
  609. * placeholder array should be the UID so we can
  610. * reconstruct the order (OPTIONAL; this array will
  611. * be built for the return value fresh if not given)
  612. * @return array $aMessageList associative array with messages. Key is the UID, value is an associative array
  613. * @author Marc Groot Koerkamp
  614. */
  615. function parseFetch(&$aResponse,$aMessageList = array()) {
  616. for ($j=0,$iCnt=count($aResponse);$j<$iCnt;++$j) {
  617. $aMsg = array();
  618. $read = implode('',$aResponse[$j]);
  619. // free up memmory
  620. unset($aResponse[$j]); /* unset does not reindex the array. the for loop is safe */
  621. /*
  622. * #id<space>FETCH<space>(
  623. */
  624. /* extract the message id */
  625. $i_space = strpos($read,' ',2);/* position 2ed <space> */
  626. $id = substr($read,2/* skip "*<space>" */,$i_space -2);
  627. $aMsg['ID'] = $id;
  628. $fetch = substr($read,$i_space+1,5);
  629. if (!is_numeric($id) && $fetch !== 'FETCH') {
  630. $aMsg['ERROR'] = $read; // sm_encode_html_special_chars should be done just before display. this is backend code
  631. break;
  632. }
  633. $i = strpos($read,'(',$i_space+5);
  634. $read = substr($read,$i+1);
  635. $i_len = strlen($read);
  636. $i = 0;
  637. while ($i < $i_len && $i !== false) {
  638. /* get argument */
  639. $read = trim(substr($read,$i));
  640. $i_len = strlen($read);
  641. $i = strpos($read,' ');
  642. $arg = substr($read,0,$i);
  643. ++$i;
  644. /*
  645. * use allcaps for imap items and lowcaps for headers as key for the $aMsg array
  646. */
  647. switch ($arg)
  648. {
  649. case 'UID':
  650. $i_pos = strpos($read,' ',$i);
  651. if (!$i_pos) {
  652. $i_pos = strpos($read,')',$i);
  653. }
  654. if ($i_pos) {
  655. $unique_id = substr($read,$i,$i_pos-$i);
  656. $i = $i_pos+1;
  657. } else {
  658. break 3;
  659. }
  660. break;
  661. case 'FLAGS':
  662. $flags = parseArray($read,$i);
  663. if (!$flags) break 3;
  664. $aFlags = array();
  665. foreach ($flags as $flag) {
  666. $flag = strtolower($flag);
  667. $aFlags[$flag] = true;
  668. }
  669. $aMsg['FLAGS'] = $aFlags;
  670. break;
  671. case 'RFC822.SIZE':
  672. $i_pos = strpos($read,' ',$i);
  673. if (!$i_pos) {
  674. $i_pos = strpos($read,')',$i);
  675. }
  676. if ($i_pos) {
  677. $aMsg['SIZE'] = substr($read,$i,$i_pos-$i);
  678. $i = $i_pos+1;
  679. } else {
  680. break 3;
  681. }
  682. break;
  683. case 'ENVELOPE':
  684. // sqimap_parse_address($read,$i,$aMsg);
  685. break; // to be implemented, moving imap code out of the Message class
  686. case 'BODYSTRUCTURE':
  687. break; // to be implemented, moving imap code out of the Message class
  688. case 'INTERNALDATE':
  689. $aMsg['INTERNALDATE'] = trim(preg_replace('/\s+/', ' ',parseString($read,$i)));
  690. break;
  691. case 'BODY.PEEK[HEADER.FIELDS':
  692. case 'BODY[HEADER.FIELDS':
  693. $i = strpos($read,'{',$i); // header is always returned as literal because it contain \n characters
  694. $header = parseString($read,$i);
  695. if ($header === false) break 2;
  696. /* First we replace all \r\n by \n, and unfold the header */
  697. $hdr = trim(str_replace(array("\r\n", "\n\t", "\n "),array("\n", ' ', ' '), $header));
  698. /* Now we can make a new header array with
  699. each element representing a headerline */
  700. $aHdr = explode("\n" , $hdr);
  701. $aReceived = array();
  702. foreach ($aHdr as $line) {
  703. $pos = strpos($line, ':');
  704. if ($pos > 0) {
  705. $field = strtolower(substr($line, 0, $pos));
  706. if (!strstr($field,' ')) { /* valid field */
  707. $value = trim(substr($line, $pos+1));
  708. switch($field) {
  709. case 'date':
  710. $aMsg['date'] = trim(preg_replace('/\s+/', ' ', $value));
  711. break;
  712. case 'x-priority': $aMsg['x-priority'] = ($value) ? (int) $value[0] : 3; break;
  713. case 'priority':
  714. case 'importance':
  715. // duplicate code with Rfc822Header.cls:parsePriority()
  716. if (!isset($aMsg['x-priority'])) {
  717. $aPrio = preg_split('/\s/',trim($value));
  718. $sPrio = strtolower(array_shift($aPrio));
  719. if (is_numeric($sPrio)) {
  720. $iPrio = (int) $sPrio;
  721. } elseif ( $sPrio == 'non-urgent' || $sPrio == 'low' ) {
  722. $iPrio = 5;
  723. } elseif ( $sPrio == 'urgent' || $sPrio == 'high' ) {
  724. $iPrio = 1;
  725. } else {
  726. // default is normal priority
  727. $iPrio = 3;
  728. }
  729. $aMsg['x-priority'] = $iPrio;
  730. }
  731. break;
  732. case 'content-type':
  733. $type = $value;
  734. if ($pos = strpos($type, ";")) {
  735. $type = substr($type, 0, $pos);
  736. }
  737. $type = explode("/", $type);
  738. if(!is_array($type) || count($type) < 2) {
  739. $aMsg['content-type'] = array('text','plain');
  740. } else {
  741. $aMsg['content-type'] = array(strtolower($type[0]),strtolower($type[1]));
  742. }
  743. break;
  744. case 'received':
  745. $aMsg['received'][] = $value;
  746. break;
  747. default:
  748. $aMsg[$field] = $value;
  749. break;
  750. }
  751. }
  752. }
  753. }
  754. break;
  755. default:
  756. ++$i;
  757. break;
  758. }
  759. }
  760. if (!empty($unique_id)) {
  761. $msgi = "$unique_id";
  762. $aMsg['UID'] = $unique_id;
  763. } else {
  764. //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
  765. $msgi = '';
  766. }
  767. $aMessageList[$msgi] = $aMsg;
  768. $aResponse[$j] = NULL;
  769. }
  770. return $aMessageList;
  771. }
  772. /**
  773. * Work in process
  774. * @private
  775. * @author Marc Groot Koerkamp
  776. */
  777. function sqimap_parse_envelope($read, &$i, &$msg) {
  778. $arg_no = 0;
  779. $arg_a = array();
  780. ++$i;
  781. for ($cnt = strlen($read); ($i < $cnt) && ($read[$i] != ')'); ++$i) {
  782. $char = strtoupper($read[$i]);
  783. switch ($char) {
  784. case '{':
  785. case '"':
  786. $arg_a[] = parseString($read,$i);
  787. ++$arg_no;
  788. break;
  789. case 'N':
  790. /* probably NIL argument */
  791. if (strtoupper(substr($read, $i, 3)) == 'NIL') {
  792. $arg_a[] = '';
  793. ++$arg_no;
  794. $i += 2;
  795. }
  796. break;
  797. case '(':
  798. /* Address structure (with group support)
  799. * Note: Group support is useless on SMTP connections
  800. * because the protocol doesn't support it
  801. */
  802. $addr_a = array();
  803. $group = '';
  804. $a=0;
  805. for (; $i < $cnt && $read[$i] != ')'; ++$i) {
  806. if ($read[$i] == '(') {
  807. $addr = sqimap_parse_address($read, $i);
  808. if (($addr[3] == '') && ($addr[2] != '')) {
  809. /* start of group */
  810. $group = $addr[2];
  811. $group_addr = $addr;
  812. $j = $a;
  813. } else if ($group && ($addr[3] == '') && ($addr[2] == '')) {
  814. /* end group */
  815. if ($a == ($j+1)) { /* no group members */
  816. $group_addr[4] = $group;
  817. $group_addr[2] = '';
  818. $group_addr[0] = "$group: Undisclosed recipients;";
  819. $addr_a[] = $group_addr;
  820. $group ='';
  821. }
  822. } else {
  823. $addr[4] = $group;
  824. $addr_a[] = $addr;
  825. }
  826. ++$a;
  827. }
  828. }
  829. $arg_a[] = $addr_a;
  830. break;
  831. default: break;
  832. }
  833. }
  834. if (count($arg_a) > 9) {
  835. $d = strtr($arg_a[0], array(' ' => ' '));
  836. $d = explode(' ', $d);
  837. if (!$arg_a[1]) $arg_a[1] = '';
  838. $msg['DATE'] = $d; /* argument 1: date */
  839. $msg['SUBJECT'] = $arg_a[1]; /* argument 2: subject */
  840. $msg['FROM'] = is_array($arg_a[2]) ? $arg_a[2][0] : ''; /* argument 3: from */
  841. $msg['SENDER'] = is_array($arg_a[3]) ? $arg_a[3][0] : ''; /* argument 4: sender */
  842. $msg['REPLY-TO'] = is_array($arg_a[4]) ? $arg_a[4][0] : ''; /* argument 5: reply-to */
  843. $msg['TO'] = $arg_a[5]; /* argument 6: to */
  844. $msg['CC'] = $arg_a[6]; /* argument 7: cc */
  845. $msg['BCC'] = $arg_a[7]; /* argument 8: bcc */
  846. $msg['IN-REPLY-TO'] = $arg_a[8]; /* argument 9: in-reply-to */
  847. $msg['MESSAGE-ID'] = $arg_a[9]; /* argument 10: message-id */
  848. }
  849. }
  850. /**
  851. * Work in process
  852. * @private
  853. * @author Marc Groot Koerkamp
  854. */
  855. function sqimap_parse_address($read, &$i) {
  856. $arg_a = array();
  857. for (; $read[$i] != ')'; ++$i) {
  858. $char = strtoupper($read[$i]);
  859. switch ($char) {
  860. case '{':
  861. case '"': $arg_a[] = parseString($read,$i); break;
  862. case 'n':
  863. case 'N':
  864. if (strtoupper(substr($read, $i, 3)) == 'NIL') {
  865. $arg_a[] = '';
  866. $i += 2;
  867. }
  868. break;
  869. default: break;
  870. }
  871. }
  872. if (count($arg_a) == 4) {
  873. return $arg_a;
  874. // $adr = new AddressStructure();
  875. // $adr->personal = $arg_a[0];
  876. // $adr->adl = $arg_a[1];
  877. // $adr->mailbox = $arg_a[2];
  878. // $adr->host = $arg_a[3];
  879. } else {
  880. $adr = '';
  881. }
  882. return $adr;
  883. }
  884. /**
  885. * Returns a message array with all the information about a message.
  886. * See the documentation folder for more information about this array.
  887. *
  888. * @param resource $imap_stream imap connection
  889. * @param integer $id uid of the message
  890. * @param string $mailbox used for error handling, can be removed because we should return an error code and generate the message elsewhere
  891. * @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)
  892. * @return mixed Message object or FALSE/error string if error occurred and $hide is set to 2/3
  893. */
  894. function sqimap_get_message($imap_stream, $id, $mailbox, $hide=0) {
  895. // typecast to int to prohibit 1:* msgs sets
  896. // Update: $id should always be sanitized into a BIGINT so this
  897. // is being removed; leaving this code here in case something goes
  898. // wrong, however
  899. //$id = (int) $id;
  900. $flags = array();
  901. $read = sqimap_run_command($imap_stream, "FETCH $id (FLAGS BODYSTRUCTURE)", true, $response, $message, TRUE);
  902. if ($read) {
  903. if (preg_match('/.+FLAGS\s\((.*)\)\s/AUi',$read[0],$regs)) {
  904. if (trim($regs[1])) {
  905. $flags = preg_split('/ /', $regs[1],-1,PREG_SPLIT_NO_EMPTY);
  906. }
  907. }
  908. } else {
  909. if ($hide == 1) exit;
  910. if ($hide == 2) return FALSE;
  911. /* the message was not found, maybe the mailbox was modified? */
  912. global $sort, $startMessage;
  913. $errmessage = _("The server couldn't find the message you requested.");
  914. if ($hide == 3) return $errmessage;
  915. $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).");
  916. /* this will include a link back to the message list */
  917. error_message($errmessage, $mailbox, $sort, (int) $startMessage);
  918. exit;
  919. }
  920. $bodystructure = implode('',$read);
  921. $msg = mime_structure($bodystructure,$flags);
  922. $read = sqimap_run_command($imap_stream, "FETCH $id BODY[HEADER]", true, $response, $message, TRUE);
  923. $rfc822_header = new Rfc822Header();
  924. $rfc822_header->parseHeader($read);
  925. $msg->rfc822_header = $rfc822_header;
  926. parse_message_entities($msg, $id, $imap_stream);
  927. return $msg;
  928. }
  929. /**
  930. * Recursively parse embedded messages (if any) in the given
  931. * message, building correct rfc822 headers for each one
  932. *
  933. * @param object $msg The message object to scan for attached messages
  934. * NOTE: this is passed by reference! Changes made
  935. * within will affect the caller's copy of $msg!
  936. * @param int $id The top-level message UID on the IMAP server, even
  937. * if the $msg being passed in is only an attached entity
  938. * thereof.
  939. * @param resource $imap_stream A live connection to the IMAP server.
  940. *
  941. * @return void
  942. *
  943. * @since 1.5.2
  944. *
  945. */
  946. function parse_message_entities(&$msg, $id, $imap_stream) {
  947. if (!empty($msg->entities)) foreach ($msg->entities as $i => $entity) {
  948. if (is_object($entity) && strtolower(get_class($entity)) == 'message') {
  949. if (!empty($entity->rfc822_header)) {
  950. $read = sqimap_run_command($imap_stream, "FETCH $id BODY[". $entity->entity_id .".HEADER]", true, $response, $message, TRUE);
  951. $rfc822_header = new Rfc822Header();
  952. $rfc822_header->parseHeader($read);
  953. $msg->entities[$i]->rfc822_header = $rfc822_header;
  954. }
  955. parse_message_entities($msg->entities[$i], $id, $imap_stream);
  956. }
  957. }
  958. }