imap_general.php 15 KB

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