imap_general.php 20 KB

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