imap_general.php 14 KB

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