imap_general.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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. if (!isset($onetimepad) || empty($onetimepad)) {
  197. sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION );
  198. }
  199. $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
  200. $host=$imap_server_address;
  201. if (($use_imap_tls == true) and (check_php_version(4,3)) and (extension_loaded('openssl'))) {
  202. /* Use TLS by prefixing "tls://" to the hostname */
  203. $imap_server_address = 'tls://' . $imap_server_address;
  204. }
  205. $imap_stream = fsockopen ( $imap_server_address, $imap_port, $error_number, $error_string, 15);
  206. /* Do some error correction */
  207. if (!$imap_stream) {
  208. if (!$hide) {
  209. set_up_language($squirrelmail_language, true);
  210. require_once(SM_PATH . 'functions/display_messages.php');
  211. $string = sprintf (_("Error connecting to IMAP server: %s.") .
  212. "<br>\r\n", $imap_server_address) .
  213. "$error_number : $error_string<br>\r\n";
  214. logout_error($string,$color);
  215. }
  216. exit;
  217. }
  218. $server_info = fgets ($imap_stream, 1024);
  219. /* Decrypt the password */
  220. $password = OneTimePadDecrypt($password, $onetimepad);
  221. if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
  222. // We're using some sort of authentication OTHER than plain or login
  223. $tag=sqimap_session_id(false);
  224. if ($imap_auth_mech == 'digest-md5') {
  225. $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
  226. } elseif ($imap_auth_mech == 'cram-md5') {
  227. $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
  228. }
  229. fputs($imap_stream,$query);
  230. $answer=sqimap_fgets($imap_stream);
  231. // Trim the "+ " off the front
  232. $response=explode(" ",$answer,3);
  233. if ($response[0] == '+') {
  234. // Got a challenge back
  235. $challenge=$response[1];
  236. if ($imap_auth_mech == 'digest-md5') {
  237. $reply = digest_md5_response($username,$password,$challenge,'imap',$host);
  238. } elseif ($imap_auth_mech == 'cram-md5') {
  239. $reply = cram_md5_response($username,$password,$challenge);
  240. }
  241. fputs($imap_stream,$reply);
  242. $read=sqimap_fgets($imap_stream);
  243. if ($imap_auth_mech == 'digest-md5') {
  244. // DIGEST-MD5 has an extra step..
  245. if (substr($read,0,1) == '+') { // OK so far..
  246. fputs($imap_stream,"\r\n");
  247. $read=sqimap_fgets($imap_stream);
  248. }
  249. }
  250. $results=explode(" ",$read,3);
  251. $response=$results[1];
  252. $message=$results[2];
  253. } else {
  254. // Fake the response, so the error trap at the bottom will work
  255. $response="BAD";
  256. $message='IMAP server does not appear to support the authentication method selected.';
  257. $message .= ' Please contact your system administrator.';
  258. }
  259. } elseif ($imap_auth_mech == 'login') {
  260. // Original IMAP login code
  261. $query = 'LOGIN "' . quoteIMAP($username) . '" "' . quoteIMAP($password) . '"';
  262. $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
  263. } elseif ($imap_auth_mech == 'plain') {
  264. /* Replace this with SASL PLAIN if it ever gets implemented */
  265. $response="BAD";
  266. $message='SquirrelMail does not support SASL PLAIN yet. Rerun conf.pl and use login instead.';
  267. } else {
  268. $response="BAD";
  269. $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
  270. }
  271. /* If the connection was not successful, lets see why */
  272. if ($response != 'OK') {
  273. if (!$hide) {
  274. if ($response != 'NO') {
  275. /* "BAD" and anything else gets reported here. */
  276. $message = htmlspecialchars($message);
  277. set_up_language($squirrelmail_language, true);
  278. require_once(SM_PATH . 'functions/display_messages.php');
  279. if ($response == 'BAD') {
  280. $string = sprintf (_("Bad request: %s")."<br>\r\n", $message);
  281. } else {
  282. $string = sprintf (_("Unknown error: %s") . "<br>\n", $message);
  283. }
  284. if (isset($read) && is_array($read)) {
  285. $string .= '<br>' . _("Read data:") . "<br>\n";
  286. foreach ($read as $line) {
  287. $string .= htmlspecialchars($line) . "<br>\n";
  288. }
  289. }
  290. error_box($string,$color);
  291. exit;
  292. } else {
  293. /*
  294. * If the user does not log in with the correct
  295. * username and password it is not possible to get the
  296. * correct locale from the user's preferences.
  297. * Therefore, apply the same hack as on the login
  298. * screen.
  299. *
  300. * $squirrelmail_language is set by a cookie when
  301. * the user selects language and logs out
  302. */
  303. set_up_language($squirrelmail_language, true);
  304. include_once(SM_PATH . 'functions/display_messages.php' );
  305. sqsession_destroy();
  306. logout_error( _("Unknown user or password incorrect.") );
  307. exit;
  308. }
  309. } else {
  310. exit;
  311. }
  312. }
  313. return $imap_stream;
  314. }
  315. /* Simply logs out the IMAP session */
  316. function sqimap_logout ($imap_stream) {
  317. /* Logout is not valid until the server returns 'BYE'
  318. * If we don't have an imap_ stream we're already logged out */
  319. if(isset($imap_stream) && $imap_stream)
  320. sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
  321. }
  322. function sqimap_capability($imap_stream, $capability='') {
  323. global $sqimap_capabilities;
  324. if (!is_array($sqimap_capabilities)) {
  325. $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
  326. $c = explode(' ', $read[0]);
  327. for ($i=2; $i < count($c); $i++) {
  328. $cap_list = explode('=', $c[$i]);
  329. if (isset($cap_list[1])) {
  330. $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
  331. } else {
  332. $sqimap_capabilities[$cap_list[0]] = TRUE;
  333. }
  334. }
  335. }
  336. if ($capability) {
  337. if (isset($sqimap_capabilities[$capability])) {
  338. return $sqimap_capabilities[$capability];
  339. } else {
  340. return false;
  341. }
  342. }
  343. return $sqimap_capabilities;
  344. }
  345. /* Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test */
  346. function sqimap_get_delimiter ($imap_stream = false) {
  347. global $sqimap_delimiter, $optional_delimiter;
  348. /* Use configured delimiter if set */
  349. if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
  350. return $optional_delimiter;
  351. }
  352. /* Do some caching here */
  353. if (!$sqimap_delimiter) {
  354. if (sqimap_capability($imap_stream, 'NAMESPACE')) {
  355. /*
  356. * According to something that I can't find, this is supposed to work on all systems
  357. * OS: This won't work in Courier IMAP.
  358. * OS: According to rfc2342 response from NAMESPACE command is:
  359. * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
  360. * OS: We want to lookup all personal NAMESPACES...
  361. */
  362. $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
  363. if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
  364. if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
  365. $pn = $data2[1];
  366. }
  367. $pna = explode(')(', $pn);
  368. while (list($k, $v) = each($pna)) {
  369. $lst = explode('"', $v);
  370. if (isset($lst[3])) {
  371. $pn[$lst[1]] = $lst[3];
  372. } else {
  373. $pn[$lst[1]] = '';
  374. }
  375. }
  376. }
  377. $sqimap_delimiter = $pn[0];
  378. } else {
  379. fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
  380. $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
  381. $quote_position = strpos ($read[0], '"');
  382. $sqimap_delimiter = substr ($read[0], $quote_position+1, 1);
  383. }
  384. }
  385. return $sqimap_delimiter;
  386. }
  387. /* Gets the number of messages in the current mailbox. */
  388. function sqimap_get_num_messages ($imap_stream, $mailbox) {
  389. $read_ary = sqimap_run_command ($imap_stream, "EXAMINE \"$mailbox\"", false, $result, $message);
  390. for ($i = 0; $i < count($read_ary); $i++) {
  391. if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
  392. return $regs[1];
  393. }
  394. }
  395. return false; //"BUG! Couldn't get number of messages in $mailbox!";
  396. }
  397. /* Returns a displayable email address.
  398. * Luke Ehresman <lehresma@css.tayloru.edu>
  399. * "Luke Ehresman" <lehresma@css.tayloru.edu>
  400. * <lehresma@css.tayloru.edu>
  401. * lehresma@css.tayloru.edu (Luke Ehresman)
  402. * lehresma@css.tayloru.edu
  403. * becomes: lehresma@css.tayloru.edu
  404. */
  405. function sqimap_find_email ($string) {
  406. if (ereg("<([^>]+)>", $string, $regs)) {
  407. $string = $regs[1];
  408. } else if (ereg("([^ ]+@[^ ]+)", $string, $regs)) {
  409. $string = $regs[1];
  410. }
  411. return trim($string);
  412. }
  413. /*
  414. * Takes the From: field and creates a displayable name.
  415. * Luke Ehresman <lkehresman@yahoo.com>
  416. * "Luke Ehresman" <lkehresman@yahoo.com>
  417. * lkehresman@yahoo.com (Luke Ehresman)
  418. * becomes: Luke Ehresman
  419. * <lkehresman@yahoo.com>
  420. * becomes: lkehresman@yahoo.com
  421. */
  422. function sqimap_find_displayable_name ($string) {
  423. $string = trim($string);
  424. if ( ereg('^(.+)<.*>', $string, $regs) ) {
  425. $orig_string = $string;
  426. $string = str_replace ('"', '', $regs[1] );
  427. if (trim($string) == '') {
  428. $string = sqimap_find_email($orig_string);
  429. }
  430. if( $string == '' || $string == ' ' ){
  431. $string = '&nbsp;';
  432. }
  433. }
  434. elseif ( ereg('\((.*)\)', $string, $regs) ) {
  435. if( ( $regs[1] == '' ) || ( $regs[1] == ' ' ) ){
  436. if ( ereg('^(.+) \(', $string, $regs) ) {
  437. $string = ereg_replace( ' \(\)$', '', $string );
  438. } else {
  439. $string = '&nbsp;';
  440. }
  441. } else {
  442. $string = $regs[1];
  443. }
  444. }
  445. else {
  446. $string = str_replace ('"', '', sqimap_find_email($string));
  447. }
  448. return trim($string);
  449. }
  450. /*
  451. * Returns the number of unseen messages in this folder
  452. */
  453. function sqimap_unseen_messages ($imap_stream, $mailbox) {
  454. $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (UNSEEN)", false, $result, $message);
  455. $i = 0;
  456. $regs = array(false, false);
  457. while (isset($read_ary[$i])) {
  458. if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
  459. break;
  460. }
  461. $i++;
  462. }
  463. return $regs[1];
  464. }
  465. /*
  466. * Returns the number of unseen/total messages in this folder
  467. */
  468. function sqimap_status_messages ($imap_stream, $mailbox) {
  469. $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (MESSAGES UNSEEN)", false, $result, $message);
  470. $i = 0;
  471. $messages = $unseen = false;
  472. $regs = array(false,false);
  473. while (isset($read_ary[$i])) {
  474. if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
  475. $unseen = $regs[1];
  476. }
  477. if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
  478. $messages = $regs[1];
  479. }
  480. $i++;
  481. }
  482. return array('MESSAGES' => $messages, 'UNSEEN'=>$unseen);
  483. }
  484. /*
  485. * Saves a message to a given folder -- used for saving sent messages
  486. */
  487. function sqimap_append ($imap_stream, $sent_folder, $length) {
  488. fputs ($imap_stream, sqimap_session_id() . " APPEND \"$sent_folder\" (\\Seen) \{$length}\r\n");
  489. $tmp = fgets ($imap_stream, 1024);
  490. }
  491. function sqimap_append_done ($imap_stream, $folder='') {
  492. global $squirrelmail_language, $color;
  493. fputs ($imap_stream, "\r\n");
  494. $tmp = fgets ($imap_stream, 1024);
  495. if (preg_match("/(.*)(BAD|NO)(.*)$/", $tmp, $regs)) {
  496. set_up_language($squirrelmail_language);
  497. require_once(SM_PATH . 'functions/display_messages.php');
  498. $reason = $regs[3];
  499. if ($regs[2] == 'NO') {
  500. $string = "<b><font color=$color[2]>\n" .
  501. _("ERROR : Could not append message to") ." $folder." .
  502. "</b><br>\n" .
  503. _("Server responded: ") .
  504. $reason . "<br>\n";
  505. if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
  506. $string .= _("Solution: ") .
  507. _("Remove unneccessary messages from your folder and start with your Trash folder.")
  508. ."<br>\n";
  509. }
  510. $string .= "</font>\n";
  511. error_box($string,$color);
  512. } else {
  513. $string = "<b><font color=$color[2]>\n" .
  514. _("ERROR : Bad or malformed request.") .
  515. "</b><br>\n" .
  516. _("Server responded: ") .
  517. $tmp . "</font><br>\n";
  518. error_box($string,$color);
  519. exit;
  520. }
  521. }
  522. }
  523. function sqimap_get_user_server ($imap_server, $username) {
  524. if (substr($imap_server, 0, 4) != "map:") {
  525. return $imap_server;
  526. }
  527. $function = substr($imap_server, 4);
  528. return $function($username);
  529. }
  530. /* This is an example that gets imapservers from yellowpages (NIS).
  531. * you can simple put map:map_yp_alias in your $imap_server_address
  532. * in config.php use your own function instead map_yp_alias to map your
  533. * LDAP whatever way to find the users imapserver. */
  534. function map_yp_alias($username) {
  535. $yp = `ypmatch $username aliases`;
  536. return chop(substr($yp, strlen($username)+1));
  537. }
  538. ?>