imap_general.php 16 KB

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