imap_messages.php 39 KB

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