imap_messages.php 38 KB

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