imap_general.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. if ( !$imap_stream ) {
  194. return false;
  195. }
  196. $server_info = fgets ($imap_stream, 1024);
  197. /* Decrypt the password */
  198. $password = OneTimePadDecrypt($password, $onetimepad);
  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. error_box($string,$color);
  208. }
  209. exit;
  210. }
  211. $query = 'LOGIN "' . quoteIMAP($username) . '" "' . quoteIMAP($password) . '"';
  212. $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
  213. /* If the connection was not successful, lets see why */
  214. if ($response != 'OK') {
  215. if (!$hide) {
  216. if ($response != 'NO') {
  217. /* "BAD" and anything else gets reported here. */
  218. set_up_language($squirrelmail_language, true);
  219. require_once(SM_PATH . 'functions/display_messages.php');
  220. if ($response == 'BAD') {
  221. $string = sprintf (_("Bad request: %s")."<br>\r\n", $message);
  222. } else {
  223. $string = sprintf (_("Unknown error: %s") . "<br>\n", $message);
  224. }
  225. $string .= '<br>' . _("Read data:") . "<br>\n";
  226. if (is_array($read)) {
  227. foreach ($read as $line) {
  228. $string .= htmlspecialchars($line) . "<br>\n";
  229. }
  230. }
  231. error_box($string,$color);
  232. exit;
  233. } else {
  234. /*
  235. * If the user does not log in with the correct
  236. * username and password it is not possible to get the
  237. * correct locale from the user's preferences.
  238. * Therefore, apply the same hack as on the login
  239. * screen.
  240. *
  241. * $squirrelmail_language is set by a cookie when
  242. * the user selects language and logs out
  243. */
  244. set_up_language($squirrelmail_language, true);
  245. include_once(SM_PATH . 'functions/display_messages.php' );
  246. sqsession_destroy();
  247. logout_error( _("Unknown user or password incorrect.") );
  248. exit;
  249. }
  250. } else {
  251. exit;
  252. }
  253. }
  254. return $imap_stream;
  255. }
  256. /* Simply logs out the IMAP session */
  257. function sqimap_logout ($imap_stream) {
  258. /* Logout is not valid until the server returns 'BYE'
  259. * If we don't have an imap_ stream we're already logged out */
  260. if(isset($imap_stream) && $imap_stream)
  261. sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
  262. }
  263. function sqimap_capability($imap_stream, $capability='') {
  264. global $sqimap_capabilities;
  265. if (!is_array($sqimap_capabilities)) {
  266. $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
  267. $c = explode(' ', $read[0]);
  268. for ($i=2; $i < count($c); $i++) {
  269. $cap_list = explode('=', $c[$i]);
  270. if (isset($cap_list[1])) {
  271. $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
  272. } else {
  273. $sqimap_capabilities[$cap_list[0]] = TRUE;
  274. }
  275. }
  276. }
  277. if ($capability) {
  278. if (isset($sqimap_capabilities[$capability])) {
  279. return $sqimap_capabilities[$capability];
  280. } else {
  281. return false;
  282. }
  283. }
  284. return $sqimap_capabilities;
  285. }
  286. /* Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test */
  287. function sqimap_get_delimiter ($imap_stream = false) {
  288. global $sqimap_delimiter, $optional_delimiter;
  289. /* Use configured delimiter if set */
  290. if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
  291. return $optional_delimiter;
  292. }
  293. /* Do some caching here */
  294. if (!$sqimap_delimiter) {
  295. if (sqimap_capability($imap_stream, 'NAMESPACE')) {
  296. /*
  297. * According to something that I can't find, this is supposed to work on all systems
  298. * OS: This won't work in Courier IMAP.
  299. * OS: According to rfc2342 response from NAMESPACE command is:
  300. * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
  301. * OS: We want to lookup all personal NAMESPACES...
  302. */
  303. $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
  304. if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
  305. if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
  306. $pn = $data2[1];
  307. }
  308. $pna = explode(')(', $pn);
  309. while (list($k, $v) = each($pna)) {
  310. $lst = explode('"', $v);
  311. if (isset($lst[3])) {
  312. $pn[$lst[1]] = $lst[3];
  313. } else {
  314. $pn[$lst[1]] = '';
  315. }
  316. }
  317. }
  318. $sqimap_delimiter = $pn[0];
  319. } else {
  320. fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
  321. $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
  322. $quote_position = strpos ($read[0], '"');
  323. $sqimap_delimiter = substr ($read[0], $quote_position+1, 1);
  324. }
  325. }
  326. return $sqimap_delimiter;
  327. }
  328. /* Gets the number of messages in the current mailbox. */
  329. function sqimap_get_num_messages ($imap_stream, $mailbox) {
  330. $read_ary = sqimap_run_command ($imap_stream, "EXAMINE \"$mailbox\"", false, $result, $message);
  331. for ($i = 0; $i < count($read_ary); $i++) {
  332. if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
  333. return $regs[1];
  334. }
  335. }
  336. return false; //"BUG! Couldn't get number of messages in $mailbox!";
  337. }
  338. /* Returns a displayable email address.
  339. * Luke Ehresman <lehresma@css.tayloru.edu>
  340. * "Luke Ehresman" <lehresma@css.tayloru.edu>
  341. * <lehresma@css.tayloru.edu>
  342. * lehresma@css.tayloru.edu (Luke Ehresman)
  343. * lehresma@css.tayloru.edu
  344. * becomes: lehresma@css.tayloru.edu
  345. */
  346. function sqimap_find_email ($string) {
  347. if (ereg("<([^>]+)>", $string, $regs)) {
  348. $string = $regs[1];
  349. } else if (ereg("([^ ]+@[^ ]+)", $string, $regs)) {
  350. $string = $regs[1];
  351. }
  352. return trim($string);
  353. }
  354. /*
  355. * Takes the From: field and creates a displayable name.
  356. * Luke Ehresman <lkehresman@yahoo.com>
  357. * "Luke Ehresman" <lkehresman@yahoo.com>
  358. * lkehresman@yahoo.com (Luke Ehresman)
  359. * becomes: Luke Ehresman
  360. * <lkehresman@yahoo.com>
  361. * becomes: lkehresman@yahoo.com
  362. */
  363. function sqimap_find_displayable_name ($string) {
  364. $string = trim($string);
  365. if ( ereg('^(.+)<.*>', $string, $regs) ) {
  366. $orig_string = $string;
  367. $string = str_replace ('"', '', $regs[1] );
  368. if (trim($string) == '') {
  369. $string = sqimap_find_email($orig_string);
  370. }
  371. if( $string == '' || $string == ' ' ){
  372. $string = '&nbsp';
  373. }
  374. }
  375. elseif ( ereg('\((.*)\)', $string, $regs) ) {
  376. if( ( $regs[1] == '' ) || ( $regs[1] == ' ' ) ){
  377. if ( ereg('^(.+) \(', $string, $regs) ) {
  378. $string = ereg_replace( ' \(\)$', '', $string );
  379. } else {
  380. $string = '&nbsp';
  381. }
  382. } else {
  383. $string = $regs[1];
  384. }
  385. }
  386. else {
  387. $string = str_replace ('"', '', sqimap_find_email($string));
  388. }
  389. return trim($string);
  390. }
  391. /*
  392. * Returns the number of unseen messages in this folder
  393. */
  394. function sqimap_unseen_messages ($imap_stream, $mailbox) {
  395. $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (UNSEEN)", false, $result, $message);
  396. $i = 0;
  397. $regs = array(false, false);
  398. while (isset($read_ary[$i])) {
  399. if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
  400. break;
  401. }
  402. $i++;
  403. }
  404. return $regs[1];
  405. }
  406. /*
  407. * Returns the number of unseen/total messages in this folder
  408. */
  409. function sqimap_status_messages ($imap_stream, $mailbox) {
  410. $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (MESSAGES UNSEEN)", false, $result, $message);
  411. $i = 0;
  412. $messages = $unseen = false;
  413. $regs = array(false,false);
  414. while (isset($read_ary[$i])) {
  415. if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
  416. $unseen = $regs[1];
  417. }
  418. if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
  419. $messages = $regs[1];
  420. }
  421. $i++;
  422. }
  423. return array('MESSAGES' => $messages, 'UNSEEN'=>$unseen);
  424. }
  425. /*
  426. * Saves a message to a given folder -- used for saving sent messages
  427. */
  428. function sqimap_append ($imap_stream, $sent_folder, $length) {
  429. fputs ($imap_stream, sqimap_session_id() . " APPEND \"$sent_folder\" (\\Seen) \{$length}\r\n");
  430. $tmp = fgets ($imap_stream, 1024);
  431. }
  432. function sqimap_append_done ($imap_stream, $folder='') {
  433. global $squirrelmail_language, $color;
  434. fputs ($imap_stream, "\r\n");
  435. $tmp = fgets ($imap_stream, 1024);
  436. if (preg_match("/(.*)(BAD|NO)(.*)$/", $tmp, $regs)) {
  437. set_up_language($squirrelmail_language);
  438. require_once(SM_PATH . 'functions/display_messages.php');
  439. $reason = $regs[3];
  440. if ($regs[2] == 'NO') {
  441. $string = "<b><font color=$color[2]>\n" .
  442. _("ERROR : Could not append message to") ." $folder." .
  443. "</b><br>\n" .
  444. _("Server responded: ") .
  445. $reason . "<br>\n";
  446. if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
  447. $string .= _("Sollution: ") .
  448. _("Remove unnessecarry messages from your folder and start with your Trash folder.")
  449. ."<br>\n";
  450. }
  451. $string .= "</font>\n";
  452. error_box($string,$color);
  453. } else {
  454. $string = "<b><font color=$color[2]>\n" .
  455. _("ERROR : Bad or malformed request.") .
  456. "</b><br>\n" .
  457. _("Server responded: ") .
  458. $tmp . "</font><br>\n";
  459. error_box($string,$color);
  460. exit;
  461. }
  462. }
  463. }
  464. function sqimap_get_user_server ($imap_server, $username) {
  465. if (substr($imap_server, 0, 4) != "map:") {
  466. return $imap_server;
  467. }
  468. $function = substr($imap_server, 4);
  469. return $function($username);
  470. }
  471. /* This is an example that gets imapservers from yellowpages (NIS).
  472. * you can simple put map:map_yp_alias in your $imap_server_address
  473. * in config.php use your own function instead map_yp_alias to map your
  474. * LDAP whatever way to find the users imapserver. */
  475. function map_yp_alias($username) {
  476. $yp = `ypmatch $username aliases`;
  477. return chop(substr($yp, strlen($username)+1));
  478. }
  479. ?>