imap_general.php 16 KB

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