imap_general.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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. require_once('../functions/display_messages.php');
  14. global $sqimap_session_id;
  15. $sqimap_session_id = 1;
  16. /* Sets an unique session id in order to avoid simultanous sessions crash. */
  17. function sqimap_session_id() {
  18. global $data_dir, $username, $sqimap_session_id;
  19. return( sprintf("A%03d", $sqimap_session_id++) );
  20. }
  21. /*
  22. * Both send a command and accept the result from the command.
  23. * This is to allow proper session number handling.
  24. */
  25. function sqimap_run_command_list ($imap_stream, $query, $handle_errors, &$response, &$message) {
  26. $sid = sqimap_session_id();
  27. fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
  28. $read = sqimap_read_data_list ($imap_stream, $sid, $handle_errors, $response, $message, $query );
  29. return $read;
  30. }
  31. function sqimap_run_command ($imap_stream, $query, $handle_errors, &$response, &$message) {
  32. $sid = sqimap_session_id();
  33. fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
  34. $read = sqimap_read_data ($imap_stream, $sid, $handle_errors, $response, $message, $query);
  35. return $read;
  36. }
  37. /*
  38. * Reads the output from the IMAP stream. If handle_errors is set to true,
  39. * this will also handle all errors that are received. If it is not set,
  40. * the errors will be sent back through $response and $message
  41. */
  42. function sqimap_read_data_list ($imap_stream, $pre, $handle_errors, &$response, &$message, $query = '') {
  43. global $color, $squirrelmail_language;
  44. $read = '';
  45. $bufsize = 9096;
  46. $resultlist = array();
  47. $more_msgs = true;
  48. while ($more_msgs) {
  49. $data = array();
  50. $total_size = 0;
  51. while (strpos($read, "\n") === false) {
  52. if(!($read .= fgets($imap_stream, $bufsize))) {
  53. break;
  54. }
  55. }
  56. /* if (ereg("^\\* [0-9]+ FETCH.*\\{([0-9]+)\\}", $read, $regs)) { */
  57. if (preg_match('/^\* [0-9]+ FETCH.*\{([0-9]+)\}/', $read, $regs)) {
  58. $size = $regs[1];
  59. /* } else if (ereg("^\\* [0-9]+ FETCH", $read, $regs)) { */
  60. } else if (preg_match('/^\* [0-9]+ FETCH/', $read, $regs)) {
  61. /* Sizeless response, probably single-line */
  62. $size = -1;
  63. $data[] = $read;
  64. $read = fgets($imap_stream, $bufsize);
  65. } else {
  66. $size = -1;
  67. }
  68. while (1) {
  69. while (strpos($read, "\n") === false) {
  70. if(!($read .= fgets($imap_stream, $bufsize))) {
  71. break;
  72. }
  73. }
  74. /* If we know the size, no need to look at the end parameters */
  75. if ($size > 0) {
  76. if ($total_size == $size) {
  77. /* We've reached the end of this 'message', switch to the next one. */
  78. $data[] = $read;
  79. break;
  80. } else if ($total_size > $size) {
  81. $difference = $total_size - $size;
  82. $total_size = $total_size - strlen($read);
  83. $data[] = substr ($read, 0, strlen($read)-$difference);
  84. $read = substr ($read, strlen($read)-$difference, strlen($read));
  85. break;
  86. } else {
  87. $data[] = $read;
  88. $read = fgets($imap_stream, $bufsize);
  89. while (strpos($read, "\n") === false) {
  90. $read .= fgets($imap_stream, $bufsize);
  91. }
  92. }
  93. $total_size += strlen($read);
  94. } else {
  95. /* if (ereg("^$pre (OK|BAD|NO)(.*)", $read, $regs) || */
  96. if (preg_match("/^$pre (OK|BAD|NO)(.*)/", $read, $regs) ||
  97. /* (($size == -1) && ereg("^\\* [0-9]+ FETCH.*", $read, $regs))) { */
  98. (($size == -1) && preg_match('/^\* [0-9]+ FETCH.*/', $read, $regs))) {
  99. break;
  100. } else if ( preg_match('/^\* OK \[PARSE.*/', $read, $regs ) ) {
  101. /*
  102. * This block has been added in order to avoid the problem
  103. * caused by the * OK [PARSE] Missing parameter answer
  104. * Please, replace it with a better parsing if you know how.
  105. * This block has been updated by
  106. * Seth E. Randall <sethr@missoulafcu.org>. Once we see
  107. * one OK [PARSE line, we just go through and keep
  108. * tossing them out until we get something different.
  109. */
  110. while ( preg_match('/^\* OK \[PARSE.*/', $read, $regs ) ) {
  111. $read = fgets($imap_stream, $bufsize);
  112. }
  113. $data[] = $read;
  114. $read = fgets ($imap_stream, $bufsize);
  115. } else if (preg_match('/^\* BYE \[ALERT\](.*)/', $read, $regs)) {
  116. /*
  117. * It seems that the IMAP server has coughed up a lung
  118. * and hung up the connection. Print any info we have
  119. * and abort.
  120. */
  121. echo _("Please contact your system administrator and report the following error:") . "<br>\n";
  122. echo $regs[1];
  123. exit;
  124. } else {
  125. $data[] = $read;
  126. $read = fgets ($imap_stream, $bufsize);
  127. }
  128. }
  129. }
  130. /*
  131. * while (($more_msgs = !ereg("^$pre (OK|BAD|NO)(.*)$", $read, $regs)) &&
  132. * !ereg("^\\* [0-9]+ FETCH.*", $read, $regs)) {
  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. displayHtmlHeader( _("Unknown user or password incorrect.") );
  230. echo "<body bgcolor=\"#ffffff\">\n";
  231. error_username_password_incorrect();
  232. session_destroy();
  233. exit;
  234. }
  235. } else {
  236. exit;
  237. }
  238. }
  239. return $imap_stream;
  240. }
  241. /* Simply logs out the IMAP session */
  242. function sqimap_logout ($imap_stream) {
  243. /* Logout is not valid until the server returns 'BYE' */
  244. sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
  245. }
  246. function sqimap_capability($imap_stream, $capability) {
  247. global $sqimap_capabilities;
  248. if (!is_array($sqimap_capabilities)) {
  249. $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
  250. $c = explode(' ', $read[0]);
  251. for ($i=2; $i < count($c); $i++) {
  252. $cap_list = explode('=', $c[$i]);
  253. if (isset($cap_list[1])) {
  254. $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
  255. } else {
  256. $sqimap_capabilities[$cap_list[0]] = TRUE;
  257. }
  258. }
  259. }
  260. if (isset($sqimap_capabilities[$capability])) {
  261. return $sqimap_capabilities[$capability];
  262. } else {
  263. return false;
  264. }
  265. }
  266. /* Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test */
  267. function sqimap_get_delimiter ($imap_stream = false) {
  268. global $sqimap_delimiter, $optional_delimiter;
  269. /* Use configured delimiter if set */
  270. if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
  271. return $optional_delimiter;
  272. }
  273. /* Do some caching here */
  274. if (!$sqimap_delimiter) {
  275. if (sqimap_capability($imap_stream, 'NAMESPACE')) {
  276. /*
  277. * According to something that I can't find, this is supposed to work on all systems
  278. * OS: This won't work in Courier IMAP.
  279. * OS: According to rfc2342 response from NAMESPACE command is:
  280. * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
  281. * OS: We want to lookup all personal NAMESPACES...
  282. */
  283. $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
  284. if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
  285. if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
  286. $pn = $data2[1];
  287. }
  288. $pna = explode(')(', $pn);
  289. while (list($k, $v) = each($pna)) {
  290. $lst = explode('"', $v);
  291. if (isset($lst[3])) {
  292. $pn[$lst[1]] = $lst[3];
  293. } else {
  294. $pn[$lst[1]] = '';
  295. }
  296. }
  297. }
  298. $sqimap_delimiter = $pn[0];
  299. } else {
  300. fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
  301. $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
  302. $quote_position = strpos ($read[0], '"');
  303. $sqimap_delimiter = substr ($read[0], $quote_position+1, 1);
  304. }
  305. }
  306. return $sqimap_delimiter;
  307. }
  308. /* Gets the number of messages in the current mailbox. */
  309. function sqimap_get_num_messages ($imap_stream, $mailbox) {
  310. $read_ary = sqimap_run_command ($imap_stream, "EXAMINE \"$mailbox\"", true, $result, $message);
  311. for ($i = 0; $i < count($read_ary); $i++) {
  312. if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
  313. return $regs[1];
  314. }
  315. }
  316. return "BUG! Couldn't get number of messages in $mailbox!";
  317. }
  318. /* Returns a displayable email address.
  319. * Luke Ehresman <lehresma@css.tayloru.edu>
  320. * "Luke Ehresman" <lehresma@css.tayloru.edu>
  321. * <lehresma@css.tayloru.edu>
  322. * lehresma@css.tayloru.edu (Luke Ehresman)
  323. * lehresma@css.tayloru.edu
  324. * becomes: lehresma@css.tayloru.edu
  325. */
  326. function sqimap_find_email ($string) {
  327. if (ereg("<([^>]+)>", $string, $regs)) {
  328. $string = $regs[1];
  329. } else if (ereg("([^ ]+@[^ ]+)", $string, $regs)) {
  330. $string = $regs[1];
  331. }
  332. return trim($string);
  333. }
  334. /*
  335. * Takes the From: field and creates a displayable name.
  336. * Luke Ehresman <lkehresman@yahoo.com>
  337. * "Luke Ehresman" <lkehresman@yahoo.com>
  338. * lkehresman@yahoo.com (Luke Ehresman)
  339. * becomes: Luke Ehresman
  340. * <lkehresman@yahoo.com>
  341. * becomes: lkehresman@yahoo.com
  342. */
  343. function sqimap_find_displayable_name ($string) {
  344. $string = trim($string);
  345. if ( ereg('^(.+)<.*>', $string, $regs) ) {
  346. $orig_string = $string;
  347. $string = str_replace ('"', '', $regs[1] );
  348. if (trim($string) == '') {
  349. $string = sqimap_find_email($orig_string);
  350. }
  351. if( $string == '' || $string == ' ' ){
  352. $string = '&nbsp';
  353. }
  354. }
  355. elseif ( ereg('\((.*)\)', $string, $regs) ) {
  356. if( ( $regs[1] == '' ) || ( $regs[1] == ' ' ) ){
  357. if ( ereg('^(.+) \(', $string, $regs) ) {
  358. $string = ereg_replace( ' \(\)$', '', $string );
  359. } else {
  360. $string = '&nbsp';
  361. }
  362. } else {
  363. $string = $regs[1];
  364. }
  365. }
  366. else {
  367. $string = str_replace ('"', '', sqimap_find_email($string));
  368. }
  369. return trim($string);
  370. }
  371. /*
  372. * Returns the number of unseen messages in this folder
  373. */
  374. function sqimap_unseen_messages ($imap_stream, $mailbox) {
  375. $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (UNSEEN)", true, $result, $message);
  376. $i = 0;
  377. while (isset($read_ary[$i])) {
  378. if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
  379. break;
  380. }
  381. $i++;
  382. }
  383. return $regs[1];
  384. }
  385. /*
  386. * Saves a message to a given folder -- used for saving sent messages
  387. */
  388. function sqimap_append ($imap_stream, $sent_folder, $length) {
  389. fputs ($imap_stream, sqimap_session_id() . " APPEND \"$sent_folder\" (\\Seen) \{$length}\r\n");
  390. $tmp = fgets ($imap_stream, 1024);
  391. }
  392. function sqimap_append_done ($imap_stream) {
  393. fputs ($imap_stream, "\r\n");
  394. $tmp = fgets ($imap_stream, 1024);
  395. }
  396. ?>