imap_general.php 18 KB

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