imap_general.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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. require_once(SM_PATH . 'functions/auth.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($unique_id = false) {
  18. global $data_dir, $username, $sqimap_session_id;
  19. if (!$unique_id) {
  20. return( sprintf("A%03d", $sqimap_session_id++) );
  21. } else {
  22. return( sprintf("A%03d", $sqimap_session_id++) . ' UID' );
  23. }
  24. }
  25. /*
  26. * Both send a command and accept the result from the command.
  27. * This is to allow proper session number handling.
  28. */
  29. function sqimap_run_command_list ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
  30. if ($imap_stream) {
  31. $sid = sqimap_session_id($unique_id);
  32. fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
  33. $read = sqimap_read_data_list ($imap_stream, $sid, $handle_errors, $response, $message, $query );
  34. return $read;
  35. } else {
  36. global $squirrelmail_language, $color;
  37. set_up_language($squirrelmail_language);
  38. require_once(SM_PATH . 'functions/display_messages.php');
  39. $string = "<b><font color=$color[2]>\n" .
  40. _("ERROR : No available imapstream.") .
  41. "</b></font>\n";
  42. error_box($string,$color);
  43. return false;
  44. }
  45. }
  46. function sqimap_run_command ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
  47. if ($imap_stream) {
  48. $sid = sqimap_session_id($unique_id);
  49. fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
  50. $read = sqimap_read_data ($imap_stream, $sid, $handle_errors, $response, $message, $query);
  51. return $read;
  52. } else {
  53. global $squirrelmail_language, $color;
  54. set_up_language($squirrelmail_language);
  55. require_once(SM_PATH . 'functions/display_messages.php');
  56. $string = "<b><font color=$color[2]>\n" .
  57. _("ERROR : No available imapstream.") .
  58. "</b></font>\n";
  59. error_box($string,$color);
  60. return false;
  61. }
  62. }
  63. /*
  64. * custom fgets function. gets a line from IMAP
  65. * no matter how big it may be
  66. */
  67. function sqimap_fgets($imap_stream) {
  68. $read = '';
  69. $buffer = 4096;
  70. $results = '';
  71. while (strpos($read, "\n") === false) {
  72. if (!($read = fgets($imap_stream, $buffer))) {
  73. break;
  74. }
  75. $results .= $read;
  76. }
  77. return $results;
  78. }
  79. /*
  80. * Reads the output from the IMAP stream. If handle_errors is set to true,
  81. * this will also handle all errors that are received. If it is not set,
  82. * the errors will be sent back through $response and $message
  83. */
  84. function sqimap_read_data_list ($imap_stream, $pre, $handle_errors, &$response, &$message, $query = '') {
  85. global $color, $squirrelmail_language;
  86. $read = '';
  87. $pre_a = explode(' ',trim($pre));
  88. $pre = $pre_a[0];
  89. $resultlist = array();
  90. $data = array();
  91. $read = sqimap_fgets($imap_stream);
  92. while (1) {
  93. switch (true) {
  94. case preg_match("/^$pre (OK|BAD|NO)(.*)$/", $read, $regs):
  95. case preg_match('/^\* (BYE \[ALERT\])(.*)$/', $read, $regs):
  96. $response = $regs[1];
  97. $message = trim($regs[2]);
  98. break 2;
  99. case preg_match("/^\* (OK \[PARSE\])(.*)$/", $read):
  100. $read = sqimap_fgets($imap_stream);
  101. break 1;
  102. case preg_match('/^\* ([0-9]+) FETCH.*/', $read, $regs):
  103. $fetch_data = array();
  104. $fetch_data[] = $read;
  105. $read = sqimap_fgets($imap_stream);
  106. while (!preg_match('/^\* [0-9]+ FETCH.*/', $read) &&
  107. !preg_match("/^$pre (OK|BAD|NO)(.*)$/", $read)) {
  108. $fetch_data[] = $read;
  109. $last = $read;
  110. $read = sqimap_fgets($imap_stream);
  111. }
  112. if (isset($last) && preg_match('/^\)/', $last)) {
  113. array_pop($fetch_data);
  114. }
  115. $resultlist[] = $fetch_data;
  116. break 1;
  117. default:
  118. $data[] = $read;
  119. $read = sqimap_fgets($imap_stream);
  120. break 1;
  121. }
  122. }
  123. if (!empty($data)) {
  124. $resultlist[] = $data;
  125. }
  126. elseif (empty($resultlist)) {
  127. $resultlist[] = array();
  128. }
  129. if ($handle_errors == false) {
  130. return( $resultlist );
  131. }
  132. elseif ($response == 'NO') {
  133. /* ignore this error from M$ exchange, it is not fatal (aka bug) */
  134. if (strstr($message, 'command resulted in') === false) {
  135. set_up_language($squirrelmail_language);
  136. require_once(SM_PATH . 'functions/display_messages.php');
  137. $string = "<b><font color=$color[2]>\n" .
  138. _("ERROR : Could not complete request.") .
  139. "</b><br>\n" .
  140. _("Query:") .
  141. $query . '<br>' .
  142. _("Reason Given: ") .
  143. $message . "</font><br>\n";
  144. error_box($string,$color);
  145. exit;
  146. }
  147. }
  148. elseif ($response == 'BAD') {
  149. set_up_language($squirrelmail_language);
  150. require_once(SM_PATH . 'functions/display_messages.php');
  151. $string = "<b><font color=$color[2]>\n" .
  152. _("ERROR : Bad or malformed request.") .
  153. "</b><br>\n" .
  154. _("Query:") .
  155. $query . '<br>' .
  156. _("Server responded: ") .
  157. $message . "</font><br>\n";
  158. error_box($string,$color);
  159. exit;
  160. }
  161. else {
  162. return $resultlist;
  163. }
  164. }
  165. function sqimap_read_data ($imap_stream, $pre, $handle_errors, &$response, &$message, $query = '') {
  166. $res = sqimap_read_data_list($imap_stream, $pre, $handle_errors, $response, $message, $query);
  167. /* sqimap_read_data should be called for one response
  168. but since it just calls sqimap_read_data_list which
  169. handles multiple responses we need to check for that
  170. and merge the $res array IF they are seperated and
  171. IF it was a FETCH response. */
  172. if (isset($res[1]) && is_array($res[1]) && isset($res[1][0])
  173. && preg_match('/^\* \d+ FETCH/', $res[1][0])) {
  174. $result = array();
  175. foreach($res as $index=>$value) {
  176. $result = array_merge($result, $res["$index"]);
  177. }
  178. }
  179. if (isset($result)) {
  180. return $result;
  181. }
  182. else {
  183. return $res[0];
  184. }
  185. }
  186. /*
  187. * Logs the user into the imap server. If $hide is set, no error messages
  188. * will be displayed. This function returns the imap connection handle.
  189. */
  190. function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
  191. global $color, $squirrelmail_language, $onetimepad, $use_imap_tls, $imap_auth_mech;
  192. $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
  193. $host=$imap_server_address;
  194. if (($use_imap_tls == true) and (check_php_version(4,3)) and (extension_loaded('openssl'))) {
  195. /* Use TLS by prefixing "tls://" to the hostname */
  196. $imap_server_address = 'tls://' . $imap_server_address;
  197. }
  198. $imap_stream = fsockopen ( $imap_server_address, $imap_port, $error_number, $error_string, 15);
  199. /* Do some error correction */
  200. if (!$imap_stream) {
  201. if (!$hide) {
  202. set_up_language($squirrelmail_language, true);
  203. require_once(SM_PATH . 'functions/display_messages.php');
  204. $string = sprintf (_("Error connecting to IMAP server: %s.") .
  205. "<br>\r\n", $imap_server_address) .
  206. "$error_number : $error_string<br>\r\n";
  207. logout_error($string,$color);
  208. }
  209. exit;
  210. }
  211. $server_info = fgets ($imap_stream, 1024);
  212. /* Decrypt the password */
  213. $password = OneTimePadDecrypt($password, $onetimepad);
  214. if ((($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) AND (extension_loaded('mhash'))) {
  215. // We're using some sort of authentication OTHER than plain
  216. $tag=sqimap_session_id(false);
  217. if ($imap_auth_mech == 'digest-md5') {
  218. $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
  219. } elseif ($imap_auth_mech == 'cram-md5') {
  220. $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
  221. }
  222. fputs($imap_stream,$query);
  223. $answer=sqimap_fgets($imap_stream);
  224. // Trim the "+ " off the front
  225. $response=explode(" ",$answer,3);
  226. if ($response[0] == '+') {
  227. // Got a challenge back
  228. $challenge=$response[1];
  229. if ($imap_auth_mech == 'digest-md5') {
  230. $reply = digest_md5_response($username,$password,$challenge,'imap',$host);
  231. } elseif ($imap_auth_mech == 'cram-md5') {
  232. $reply = cram_md5_response($username,$password,$challenge);
  233. }
  234. fputs($imap_stream,$reply);
  235. $read=sqimap_fgets($imap_stream);
  236. if ($imap_auth_mech == 'digest-md5') {
  237. // DIGEST-MD5 has an extra step..
  238. if (substr($read,0,1) == '+') { // OK so far..
  239. fputs($imap_stream,"\r\n");
  240. $read=sqimap_fgets($imap_stream);
  241. }
  242. }
  243. $results=explode(" ",$read,3);
  244. $response=$results[1];
  245. $message=$results[2];
  246. } else {
  247. // Fake the response, so the error trap at the bottom will work
  248. $response="BAD";
  249. $message='IMAP server does not appear to support the authentication method selected.';
  250. $message .= ' Please contact your system administrator.';
  251. }
  252. } else {
  253. // Original PLAIN login code
  254. $query = 'LOGIN "' . quoteIMAP($username) . '" "' . quoteIMAP($password) . '"';
  255. $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
  256. }
  257. /* If the connection was not successful, lets see why */
  258. if ($response != 'OK') {
  259. if (!$hide) {
  260. if ($response != 'NO') {
  261. /* "BAD" and anything else gets reported here. */
  262. set_up_language($squirrelmail_language, true);
  263. require_once(SM_PATH . 'functions/display_messages.php');
  264. if ($response == 'BAD') {
  265. $string = sprintf (_("Bad request: %s")."<br>\r\n", $message);
  266. } else {
  267. $string = sprintf (_("Unknown error: %s") . "<br>\n", $message);
  268. }
  269. $string .= '<br>' . _("Read data:") . "<br>\n";
  270. if (is_array($read)) {
  271. foreach ($read as $line) {
  272. $string .= htmlspecialchars($line) . "<br>\n";
  273. }
  274. }
  275. error_box($string,$color);
  276. exit;
  277. } else {
  278. /*
  279. * If the user does not log in with the correct
  280. * username and password it is not possible to get the
  281. * correct locale from the user's preferences.
  282. * Therefore, apply the same hack as on the login
  283. * screen.
  284. *
  285. * $squirrelmail_language is set by a cookie when
  286. * the user selects language and logs out
  287. */
  288. set_up_language($squirrelmail_language, true);
  289. include_once(SM_PATH . 'functions/display_messages.php' );
  290. sqsession_destroy();
  291. logout_error( _("Unknown user or password incorrect.") );
  292. exit;
  293. }
  294. } else {
  295. exit;
  296. }
  297. }
  298. return $imap_stream;
  299. }
  300. /* Simply logs out the IMAP session */
  301. function sqimap_logout ($imap_stream) {
  302. /* Logout is not valid until the server returns 'BYE'
  303. * If we don't have an imap_ stream we're already logged out */
  304. if(isset($imap_stream) && $imap_stream)
  305. sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
  306. }
  307. function sqimap_capability($imap_stream, $capability='') {
  308. global $sqimap_capabilities;
  309. if (!is_array($sqimap_capabilities)) {
  310. $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
  311. $c = explode(' ', $read[0]);
  312. for ($i=2; $i < count($c); $i++) {
  313. $cap_list = explode('=', $c[$i]);
  314. if (isset($cap_list[1])) {
  315. $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
  316. } else {
  317. $sqimap_capabilities[$cap_list[0]] = TRUE;
  318. }
  319. }
  320. }
  321. if ($capability) {
  322. if (isset($sqimap_capabilities[$capability])) {
  323. return $sqimap_capabilities[$capability];
  324. } else {
  325. return false;
  326. }
  327. }
  328. return $sqimap_capabilities;
  329. }
  330. /* Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test */
  331. function sqimap_get_delimiter ($imap_stream = false) {
  332. global $sqimap_delimiter, $optional_delimiter;
  333. /* Use configured delimiter if set */
  334. if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
  335. return $optional_delimiter;
  336. }
  337. /* Do some caching here */
  338. if (!$sqimap_delimiter) {
  339. if (sqimap_capability($imap_stream, 'NAMESPACE')) {
  340. /*
  341. * According to something that I can't find, this is supposed to work on all systems
  342. * OS: This won't work in Courier IMAP.
  343. * OS: According to rfc2342 response from NAMESPACE command is:
  344. * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
  345. * OS: We want to lookup all personal NAMESPACES...
  346. */
  347. $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
  348. if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
  349. if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
  350. $pn = $data2[1];
  351. }
  352. $pna = explode(')(', $pn);
  353. while (list($k, $v) = each($pna)) {
  354. $lst = explode('"', $v);
  355. if (isset($lst[3])) {
  356. $pn[$lst[1]] = $lst[3];
  357. } else {
  358. $pn[$lst[1]] = '';
  359. }
  360. }
  361. }
  362. $sqimap_delimiter = $pn[0];
  363. } else {
  364. fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
  365. $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
  366. $quote_position = strpos ($read[0], '"');
  367. $sqimap_delimiter = substr ($read[0], $quote_position+1, 1);
  368. }
  369. }
  370. return $sqimap_delimiter;
  371. }
  372. /* Gets the number of messages in the current mailbox. */
  373. function sqimap_get_num_messages ($imap_stream, $mailbox) {
  374. $read_ary = sqimap_run_command ($imap_stream, "EXAMINE \"$mailbox\"", false, $result, $message);
  375. for ($i = 0; $i < count($read_ary); $i++) {
  376. if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
  377. return $regs[1];
  378. }
  379. }
  380. return false; //"BUG! Couldn't get number of messages in $mailbox!";
  381. }
  382. /* Returns a displayable email address.
  383. * Luke Ehresman <lehresma@css.tayloru.edu>
  384. * "Luke Ehresman" <lehresma@css.tayloru.edu>
  385. * <lehresma@css.tayloru.edu>
  386. * lehresma@css.tayloru.edu (Luke Ehresman)
  387. * lehresma@css.tayloru.edu
  388. * becomes: lehresma@css.tayloru.edu
  389. */
  390. function sqimap_find_email ($string) {
  391. if (ereg("<([^>]+)>", $string, $regs)) {
  392. $string = $regs[1];
  393. } else if (ereg("([^ ]+@[^ ]+)", $string, $regs)) {
  394. $string = $regs[1];
  395. }
  396. return trim($string);
  397. }
  398. /*
  399. * Takes the From: field and creates a displayable name.
  400. * Luke Ehresman <lkehresman@yahoo.com>
  401. * "Luke Ehresman" <lkehresman@yahoo.com>
  402. * lkehresman@yahoo.com (Luke Ehresman)
  403. * becomes: Luke Ehresman
  404. * <lkehresman@yahoo.com>
  405. * becomes: lkehresman@yahoo.com
  406. */
  407. function sqimap_find_displayable_name ($string) {
  408. $string = trim($string);
  409. if ( ereg('^(.+)<.*>', $string, $regs) ) {
  410. $orig_string = $string;
  411. $string = str_replace ('"', '', $regs[1] );
  412. if (trim($string) == '') {
  413. $string = sqimap_find_email($orig_string);
  414. }
  415. if( $string == '' || $string == ' ' ){
  416. $string = '&nbsp';
  417. }
  418. }
  419. elseif ( ereg('\((.*)\)', $string, $regs) ) {
  420. if( ( $regs[1] == '' ) || ( $regs[1] == ' ' ) ){
  421. if ( ereg('^(.+) \(', $string, $regs) ) {
  422. $string = ereg_replace( ' \(\)$', '', $string );
  423. } else {
  424. $string = '&nbsp';
  425. }
  426. } else {
  427. $string = $regs[1];
  428. }
  429. }
  430. else {
  431. $string = str_replace ('"', '', sqimap_find_email($string));
  432. }
  433. return trim($string);
  434. }
  435. /*
  436. * Returns the number of unseen messages in this folder
  437. */
  438. function sqimap_unseen_messages ($imap_stream, $mailbox) {
  439. $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (UNSEEN)", false, $result, $message);
  440. $i = 0;
  441. $regs = array(false, false);
  442. while (isset($read_ary[$i])) {
  443. if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
  444. break;
  445. }
  446. $i++;
  447. }
  448. return $regs[1];
  449. }
  450. /*
  451. * Returns the number of unseen/total messages in this folder
  452. */
  453. function sqimap_status_messages ($imap_stream, $mailbox) {
  454. $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (MESSAGES UNSEEN)", false, $result, $message);
  455. $i = 0;
  456. $messages = $unseen = false;
  457. $regs = array(false,false);
  458. while (isset($read_ary[$i])) {
  459. if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
  460. $unseen = $regs[1];
  461. }
  462. if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
  463. $messages = $regs[1];
  464. }
  465. $i++;
  466. }
  467. return array('MESSAGES' => $messages, 'UNSEEN'=>$unseen);
  468. }
  469. /*
  470. * Saves a message to a given folder -- used for saving sent messages
  471. */
  472. function sqimap_append ($imap_stream, $sent_folder, $length) {
  473. fputs ($imap_stream, sqimap_session_id() . " APPEND \"$sent_folder\" (\\Seen) \{$length}\r\n");
  474. $tmp = fgets ($imap_stream, 1024);
  475. }
  476. function sqimap_append_done ($imap_stream, $folder='') {
  477. global $squirrelmail_language, $color;
  478. fputs ($imap_stream, "\r\n");
  479. $tmp = fgets ($imap_stream, 1024);
  480. if (preg_match("/(.*)(BAD|NO)(.*)$/", $tmp, $regs)) {
  481. set_up_language($squirrelmail_language);
  482. require_once(SM_PATH . 'functions/display_messages.php');
  483. $reason = $regs[3];
  484. if ($regs[2] == 'NO') {
  485. $string = "<b><font color=$color[2]>\n" .
  486. _("ERROR : Could not append message to") ." $folder." .
  487. "</b><br>\n" .
  488. _("Server responded: ") .
  489. $reason . "<br>\n";
  490. if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
  491. $string .= _("Solution: ") .
  492. _("Remove unneccessary messages from your folder and start with your Trash folder.")
  493. ."<br>\n";
  494. }
  495. $string .= "</font>\n";
  496. error_box($string,$color);
  497. } else {
  498. $string = "<b><font color=$color[2]>\n" .
  499. _("ERROR : Bad or malformed request.") .
  500. "</b><br>\n" .
  501. _("Server responded: ") .
  502. $tmp . "</font><br>\n";
  503. error_box($string,$color);
  504. exit;
  505. }
  506. }
  507. }
  508. function sqimap_get_user_server ($imap_server, $username) {
  509. if (substr($imap_server, 0, 4) != "map:") {
  510. return $imap_server;
  511. }
  512. $function = substr($imap_server, 4);
  513. return $function($username);
  514. }
  515. /* This is an example that gets imapservers from yellowpages (NIS).
  516. * you can simple put map:map_yp_alias in your $imap_server_address
  517. * in config.php use your own function instead map_yp_alias to map your
  518. * LDAP whatever way to find the users imapserver. */
  519. function map_yp_alias($username) {
  520. $yp = `ypmatch $username aliases`;
  521. return chop(substr($yp, strlen($username)+1));
  522. }
  523. ?>