imap_messages.php 39 KB

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