imap_general.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. <?php
  2. /**
  3. * imap_general.php
  4. *
  5. * Copyright (c) 1999-2002 The SquirrelMail Project Team
  6. * Licensed under the GNU GPL. For full terms see the file COPYING.
  7. *
  8. * This implements all functions that do general imap functions.
  9. *
  10. * $Id$
  11. */
  12. require_once('../functions/page_header.php');
  13. global $sqimap_session_id;
  14. $sqimap_session_id = 1;
  15. /* Sets an unique session id in order to avoid simultanous sessions crash. */
  16. function sqimap_session_id($unique_id = false) {
  17. global $data_dir, $username, $sqimap_session_id;
  18. if (!$unique_id) {
  19. return( sprintf("A%03d", $sqimap_session_id++) );
  20. } else {
  21. return( sprintf("A%03d", $sqimap_session_id++) . ' UID' );
  22. }
  23. }
  24. /*
  25. * Both send a command and accept the result from the command.
  26. * This is to allow proper session number handling.
  27. */
  28. function sqimap_run_command_list ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
  29. $sid = sqimap_session_id($unique_id);
  30. fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
  31. $read = sqimap_read_data_list ($imap_stream, $sid, $handle_errors, $response, $message, $query );
  32. return $read;
  33. }
  34. function sqimap_run_command ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
  35. $sid = sqimap_session_id($unique_id);
  36. fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
  37. $read = sqimap_read_data ($imap_stream, $sid, $handle_errors, $response, $message, $query);
  38. return $read;
  39. }
  40. /*
  41. * Reads the output from the IMAP stream. If handle_errors is set to true,
  42. * this will also handle all errors that are received. If it is not set,
  43. * the errors will be sent back through $response and $message
  44. */
  45. function sqimap_read_data_list ($imap_stream, $pre, $handle_errors, &$response, &$message, $query = '') {
  46. global $color, $squirrelmail_language;
  47. $read = '';
  48. $bufsize = 9096;
  49. $resultlist = array();
  50. $pre_a = explode(' ',trim($pre));
  51. $pre = $pre_a[0];
  52. $more_msgs = true;
  53. while ($more_msgs) {
  54. $data = array();
  55. $total_size = 0;
  56. while (strpos($read, "\n") === false) {
  57. if(!($read .= fgets($imap_stream, $bufsize))) {
  58. break;
  59. }
  60. }
  61. if (preg_match('/^\* [0-9]+ FETCH.*\{([0-9]+)\}/', $read, $regs)) {
  62. $size = $regs[1];
  63. } else if (preg_match('/^\* [0-9]+ FETCH/', $read, $regs)) {
  64. /* Sizeless response, probably single-line */
  65. $size = -1;
  66. $data[] = $read;
  67. $read = fgets($imap_stream, $bufsize);
  68. } else {
  69. $size = -1;
  70. }
  71. while (1) {
  72. while (strpos($read, "\n") === false) {
  73. if(!($read .= fgets($imap_stream, $bufsize))) {
  74. break;
  75. }
  76. }
  77. /* If we know the size, no need to look at the end parameters */
  78. /* In case of a totalsize > size we do have to look at the end
  79. parameters because there can exists literals inside bodystructures.
  80. */
  81. if ($size > 0) {
  82. if ($total_size == $size) {
  83. /* We've reached the end of this 'message', switch to the next one. */
  84. $data[] = $read;
  85. break;
  86. } else if ($total_size > $size) {
  87. $size = -1; /* switch to end parameters in case of literals inside a bodystructure */
  88. $difference = $total_size - $size;
  89. $total_size = $total_size - strlen($read);
  90. $data[] = substr ($read, 0, strlen($read)-$difference);
  91. $read = substr ($read, strlen($read)-$difference, strlen($read));
  92. } else {
  93. $data[] = $read;
  94. $read = fgets($imap_stream, $bufsize);
  95. while (strpos($read, "\n") === false) {
  96. $read .= fgets($imap_stream, $bufsize);
  97. }
  98. }
  99. $total_size += strlen($read);
  100. } else {
  101. if (preg_match("/^$pre (OK|BAD|NO)(.*)/", $read, $regs) ||
  102. (($size == -1) && preg_match('/^\* [0-9]+ FETCH.*/', $read, $regs))) {
  103. break;
  104. } else if ( preg_match('/^\* OK \[PARSE.*/', $read, $regs ) ) {
  105. /*
  106. * This block has been added in order to avoid the problem
  107. * caused by the * OK [PARSE] Missing parameter answer
  108. * Please, replace it with a better parsing if you know how.
  109. * This block has been updated by
  110. * Seth E. Randall <sethr@missoulafcu.org>. Once we see
  111. * one OK [PARSE line, we just go through and keep
  112. * tossing them out until we get something different.
  113. */
  114. while ( preg_match('/^\* OK \[PARSE.*/', $read, $regs ) ) {
  115. $read = fgets($imap_stream, $bufsize);
  116. }
  117. $data[] = $read;
  118. $read = fgets ($imap_stream, $bufsize);
  119. } else if (preg_match('/^\* BYE \[ALERT\](.*)/', $read, $regs)) {
  120. /*
  121. * It seems that the IMAP server has coughed up a lung
  122. * and hung up the connection. Print any info we have
  123. * and abort.
  124. */
  125. echo _("Please contact your system administrator and report the following error:") . "<br>\n";
  126. echo $regs[1];
  127. exit;
  128. } else {
  129. $data[] = $read;
  130. $read = fgets ($imap_stream, $bufsize);
  131. }
  132. }
  133. }
  134. while (($more_msgs = !preg_match("/^$pre (OK|BAD|NO)(.*)$/", $read, $regs)) &&
  135. !preg_match("/^\* [0-9]+ FETCH.*/", $read, $regs)) {
  136. $read = fgets($imap_stream, $bufsize);
  137. }
  138. $resultlist[] = $data;
  139. }
  140. $response = $regs[1];
  141. $message = trim($regs[2]);
  142. if ($handle_errors == false) {
  143. return( $resultlist );
  144. } else if ($response == 'NO') {
  145. /* ignore this error from M$ exchange, it is not fatal (aka bug) */
  146. if (strstr($message, 'command resulted in') === false) {
  147. set_up_language($squirrelmail_language);
  148. echo "<br><b><font color=$color[2]>\n" .
  149. _("ERROR : Could not complete request.") .
  150. "</b><br>\n" .
  151. _("Query:") .
  152. $query . '<br>' .
  153. _("Reason Given: ") .
  154. $message . "</font><br>\n";
  155. exit;
  156. }
  157. } else if ($response == 'BAD') {
  158. set_up_language($squirrelmail_language);
  159. echo "<br><b><font color=$color[2]>\n" .
  160. _("ERROR : Bad or malformed request.") .
  161. "</b><br>\n" .
  162. _("Query:") .
  163. $query . '<br>' .
  164. _("Server responded: ") .
  165. $message . "</font><br>\n";
  166. exit;
  167. } else {
  168. return $resultlist;
  169. }
  170. }
  171. function sqimap_read_data ($imap_stream, $pre, $handle_errors, &$response, &$message, $query = '') {
  172. $res = sqimap_read_data_list($imap_stream, $pre, $handle_errors, $response, $message, $query);
  173. return $res[0];
  174. }
  175. /*
  176. * Logs the user into the imap server. If $hide is set, no error messages
  177. * will be displayed. This function returns the imap connection handle.
  178. */
  179. function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
  180. global $color, $squirrelmail_language, $HTTP_ACCEPT_LANGUAGE, $onetimepad;
  181. $imap_stream = fsockopen ( $imap_server_address, $imap_port, $error_number, $error_string, 15);
  182. if ( !$imap_stream ) {
  183. return false;
  184. }
  185. $server_info = fgets ($imap_stream, 1024);
  186. /* Decrypt the password */
  187. $password = OneTimePadDecrypt($password, $onetimepad);
  188. /* Do some error correction */
  189. if (!$imap_stream) {
  190. if (!$hide) {
  191. set_up_language($squirrelmail_language, true);
  192. printf (_("Error connecting to IMAP server: %s.")."<br>\r\n", $imap_server_address);
  193. echo "$error_number : $error_string<br>\r\n";
  194. }
  195. exit;
  196. }
  197. $query = 'LOGIN "' . quoteIMAP($username) . '" "' . quoteIMAP($password) . '"';
  198. $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
  199. /* If the connection was not successful, lets see why */
  200. if ($response != 'OK') {
  201. if (!$hide) {
  202. if ($response != 'NO') {
  203. /* "BAD" and anything else gets reported here. */
  204. set_up_language($squirrelmail_language, true);
  205. if ($response == 'BAD') {
  206. printf (_("Bad request: %s")."<br>\r\n", $message);
  207. } else {
  208. printf (_("Unknown error: %s") . "<br>\n", $message);
  209. }
  210. echo '<br>' . _("Read data:") . "<br>\n";
  211. if (is_array($read)) {
  212. foreach ($read as $line) {
  213. echo htmlspecialchars($line) . "<br>\n";
  214. }
  215. }
  216. exit;
  217. } else {
  218. /*
  219. * If the user does not log in with the correct
  220. * username and password it is not possible to get the
  221. * correct locale from the user's preferences.
  222. * Therefore, apply the same hack as on the login
  223. * screen.
  224. *
  225. * $squirrelmail_language is set by a cookie when
  226. * the user selects language and logs out
  227. */
  228. set_up_language($squirrelmail_language, true);
  229. include_once( '../functions/display_messages.php' );
  230. logout_error( _("Unknown user or password incorrect.") );
  231. session_destroy();
  232. exit;
  233. }
  234. } else {
  235. exit;
  236. }
  237. }
  238. return $imap_stream;
  239. }
  240. /* Simply logs out the IMAP session */
  241. function sqimap_logout ($imap_stream) {
  242. /* Logout is not valid until the server returns 'BYE' */
  243. sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
  244. }
  245. function sqimap_capability($imap_stream, $capability='') {
  246. global $sqimap_capabilities;
  247. if (!is_array($sqimap_capabilities)) {
  248. $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
  249. $c = explode(' ', $read[0]);
  250. for ($i=2; $i < count($c); $i++) {
  251. $cap_list = explode('=', $c[$i]);
  252. if (isset($cap_list[1])) {
  253. $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
  254. } else {
  255. $sqimap_capabilities[$cap_list[0]] = TRUE;
  256. }
  257. }
  258. }
  259. if ($capability) {
  260. if (isset($sqimap_capabilities[$capability])) {
  261. return $sqimap_capabilities[$capability];
  262. } else {
  263. return false;
  264. }
  265. }
  266. return $sqimap_capabilities;
  267. }
  268. /* Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test */
  269. function sqimap_get_delimiter ($imap_stream = false) {
  270. global $sqimap_delimiter, $optional_delimiter;
  271. /* Use configured delimiter if set */
  272. if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
  273. return $optional_delimiter;
  274. }
  275. /* Do some caching here */
  276. if (!$sqimap_delimiter) {
  277. if (sqimap_capability($imap_stream, 'NAMESPACE')) {
  278. /*
  279. * According to something that I can't find, this is supposed to work on all systems
  280. * OS: This won't work in Courier IMAP.
  281. * OS: According to rfc2342 response from NAMESPACE command is:
  282. * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
  283. * OS: We want to lookup all personal NAMESPACES...
  284. */
  285. $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
  286. if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
  287. if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
  288. $pn = $data2[1];
  289. }
  290. $pna = explode(')(', $pn);
  291. while (list($k, $v) = each($pna)) {
  292. $lst = explode('"', $v);
  293. if (isset($lst[3])) {
  294. $pn[$lst[1]] = $lst[3];
  295. } else {
  296. $pn[$lst[1]] = '';
  297. }
  298. }
  299. }
  300. $sqimap_delimiter = $pn[0];
  301. } else {
  302. fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
  303. $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
  304. $quote_position = strpos ($read[0], '"');
  305. $sqimap_delimiter = substr ($read[0], $quote_position+1, 1);
  306. }
  307. }
  308. return $sqimap_delimiter;
  309. }
  310. /* Gets the number of messages in the current mailbox. */
  311. function sqimap_get_num_messages ($imap_stream, $mailbox) {
  312. $read_ary = sqimap_run_command ($imap_stream, "EXAMINE \"$mailbox\"", true, $result, $message);
  313. for ($i = 0; $i < count($read_ary); $i++) {
  314. if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
  315. return $regs[1];
  316. }
  317. }
  318. return "BUG! Couldn't get number of messages in $mailbox!";
  319. }
  320. /* Returns a displayable email address.
  321. * Luke Ehresman <lehresma@css.tayloru.edu>
  322. * "Luke Ehresman" <lehresma@css.tayloru.edu>
  323. * <lehresma@css.tayloru.edu>
  324. * lehresma@css.tayloru.edu (Luke Ehresman)
  325. * lehresma@css.tayloru.edu
  326. * becomes: lehresma@css.tayloru.edu
  327. */
  328. function sqimap_find_email ($string) {
  329. if (ereg("<([^>]+)>", $string, $regs)) {
  330. $string = $regs[1];
  331. } else if (ereg("([^ ]+@[^ ]+)", $string, $regs)) {
  332. $string = $regs[1];
  333. }
  334. return trim($string);
  335. }
  336. /*
  337. * Takes the From: field and creates a displayable name.
  338. * Luke Ehresman <lkehresman@yahoo.com>
  339. * "Luke Ehresman" <lkehresman@yahoo.com>
  340. * lkehresman@yahoo.com (Luke Ehresman)
  341. * becomes: Luke Ehresman
  342. * <lkehresman@yahoo.com>
  343. * becomes: lkehresman@yahoo.com
  344. */
  345. function sqimap_find_displayable_name ($string) {
  346. $string = trim($string);
  347. if ( ereg('^(.+)<.*>', $string, $regs) ) {
  348. $orig_string = $string;
  349. $string = str_replace ('"', '', $regs[1] );
  350. if (trim($string) == '') {
  351. $string = sqimap_find_email($orig_string);
  352. }
  353. if( $string == '' || $string == ' ' ){
  354. $string = '&nbsp';
  355. }
  356. }
  357. elseif ( ereg('\((.*)\)', $string, $regs) ) {
  358. if( ( $regs[1] == '' ) || ( $regs[1] == ' ' ) ){
  359. if ( ereg('^(.+) \(', $string, $regs) ) {
  360. $string = ereg_replace( ' \(\)$', '', $string );
  361. } else {
  362. $string = '&nbsp';
  363. }
  364. } else {
  365. $string = $regs[1];
  366. }
  367. }
  368. else {
  369. $string = str_replace ('"', '', sqimap_find_email($string));
  370. }
  371. return trim($string);
  372. }
  373. /*
  374. * Returns the number of unseen messages in this folder
  375. */
  376. function sqimap_unseen_messages ($imap_stream, $mailbox) {
  377. $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (UNSEEN)", true, $result, $message);
  378. $i = 0;
  379. while (isset($read_ary[$i])) {
  380. if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
  381. break;
  382. }
  383. $i++;
  384. }
  385. return $regs[1];
  386. }
  387. /*
  388. * Saves a message to a given folder -- used for saving sent messages
  389. */
  390. function sqimap_append ($imap_stream, $sent_folder, $length) {
  391. fputs ($imap_stream, sqimap_session_id() . " APPEND \"$sent_folder\" (\\Seen) \{$length}\r\n");
  392. $tmp = fgets ($imap_stream, 1024);
  393. }
  394. function sqimap_append_done ($imap_stream) {
  395. fputs ($imap_stream, "\r\n");
  396. $tmp = fgets ($imap_stream, 1024);
  397. }
  398. ?>