PageRenderTime 45ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/tags/rel-1_4_7/squirrelmail/functions/imap_general.php

#
PHP | 953 lines | 748 code | 53 blank | 152 comment | 181 complexity | 09d6b3c77915f0a90f743502d140b1a1 MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0
  1. <?php
  2. /**
  3. * imap_general.php
  4. *
  5. * This implements all functions that do general IMAP functions.
  6. *
  7. * @copyright &copy; 1999-2006 The SquirrelMail Project Team
  8. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  9. * @version $Id: imap_general.php 11307 2006-06-26 15:08:59Z kink $
  10. * @package squirrelmail
  11. * @subpackage imap
  12. */
  13. /** Includes.. */
  14. require_once(SM_PATH . 'functions/page_header.php');
  15. require_once(SM_PATH . 'functions/auth.php');
  16. /**
  17. * Generates a new session ID by incrementing the last one used;
  18. * this ensures that each command has a unique ID.
  19. * @param bool unique_id
  20. * @return string IMAP session id of the form 'A000'.
  21. */
  22. function sqimap_session_id($unique_id = FALSE) {
  23. static $sqimap_session_id = 1;
  24. if (!$unique_id) {
  25. return( sprintf("A%03d", $sqimap_session_id++) );
  26. } else {
  27. return( sprintf("A%03d", $sqimap_session_id++) . ' UID' );
  28. }
  29. }
  30. /**
  31. * Both send a command and accept the result from the command.
  32. * This is to allow proper session number handling.
  33. */
  34. function sqimap_run_command_list ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
  35. if ($imap_stream) {
  36. $sid = sqimap_session_id($unique_id);
  37. fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
  38. $read = sqimap_read_data_list ($imap_stream, $sid, $handle_errors, $response, $message, $query );
  39. return $read;
  40. } else {
  41. global $squirrelmail_language, $color;
  42. set_up_language($squirrelmail_language);
  43. require_once(SM_PATH . 'functions/display_messages.php');
  44. $string = "<b><font color=\"$color[2]\">\n" .
  45. _("ERROR: No available IMAP stream.") .
  46. "</b></font>\n";
  47. error_box($string,$color);
  48. return false;
  49. }
  50. }
  51. function sqimap_run_command ($imap_stream, $query, $handle_errors, &$response,
  52. &$message, $unique_id = false,$filter=false,
  53. $outputstream=false,$no_return=false) {
  54. if ($imap_stream) {
  55. $sid = sqimap_session_id($unique_id);
  56. fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
  57. $read = sqimap_read_data ($imap_stream, $sid, $handle_errors, $response,
  58. $message, $query,$filter,$outputstream,$no_return);
  59. return $read;
  60. } else {
  61. global $squirrelmail_language, $color;
  62. set_up_language($squirrelmail_language);
  63. require_once(SM_PATH . 'functions/display_messages.php');
  64. $string = "<b><font color=\"$color[2]\">\n" .
  65. _("ERROR: No available IMAP stream.") .
  66. "</b></font>\n";
  67. error_box($string,$color);
  68. return false;
  69. }
  70. }
  71. /**
  72. * Custom fgets function: gets a line from the IMAP server,
  73. * no matter how big it may be.
  74. * @param stream imap_stream the stream to read from
  75. * @return string a line
  76. */
  77. function sqimap_fgets($imap_stream) {
  78. $read = '';
  79. $buffer = 4096;
  80. $results = '';
  81. $offset = 0;
  82. while (strpos($results, "\r\n", $offset) === false) {
  83. if (!($read = fgets($imap_stream, $buffer))) {
  84. /* this happens in case of an error */
  85. /* reset $results because it's useless */
  86. $results = false;
  87. break;
  88. }
  89. if ( $results != '' ) {
  90. $offset = strlen($results) - 1;
  91. }
  92. $results .= $read;
  93. }
  94. return $results;
  95. }
  96. function sqimap_fread($imap_stream,$iSize,$filter=false,
  97. $outputstream=false, $no_return=false) {
  98. if (!$filter || !$outputstream) {
  99. $iBufferSize = $iSize;
  100. } else {
  101. // see php bug 24033. They changed fread behaviour %$^&$%
  102. $iBufferSize = 7800; // multiple of 78 in case of base64 decoding.
  103. }
  104. if ($iSize < $iBufferSize) {
  105. $iBufferSize = $iSize;
  106. }
  107. $iRetrieved = 0;
  108. $results = '';
  109. $sRead = $sReadRem = '';
  110. // NB: fread can also stop at end of a packet on sockets.
  111. while ($iRetrieved < $iSize) {
  112. $sRead = fread($imap_stream,$iBufferSize);
  113. $iLength = strlen($sRead);
  114. $iRetrieved += $iLength ;
  115. $iRemaining = $iSize - $iRetrieved;
  116. if ($iRemaining < $iBufferSize) {
  117. $iBufferSize = $iRemaining;
  118. }
  119. if ($sRead == '') {
  120. $results = false;
  121. break;
  122. }
  123. if ($sReadRem != '') {
  124. $sRead = $sReadRem . $sRead;
  125. $sReadRem = '';
  126. }
  127. if ($filter && $sRead != '') {
  128. // in case the filter is base64 decoding we return a remainder
  129. $sReadRem = $filter($sRead);
  130. }
  131. if ($outputstream && $sRead != '') {
  132. if (is_resource($outputstream)) {
  133. fwrite($outputstream,$sRead);
  134. } else if ($outputstream == 'php://stdout') {
  135. echo $sRead;
  136. }
  137. }
  138. if ($no_return) {
  139. $sRead = '';
  140. } else {
  141. $results .= $sRead;
  142. }
  143. }
  144. return $results;
  145. }
  146. /**
  147. * Reads the output from the IMAP stream. If handle_errors is set to true,
  148. * this will also handle all errors that are received. If it is not set,
  149. * the errors will be sent back through $response and $message.
  150. */
  151. function sqimap_read_data_list ($imap_stream, $tag_uid, $handle_errors,
  152. &$response, &$message, $query = '',
  153. $filter = false, $outputstream = false, $no_return = false) {
  154. global $color, $squirrelmail_language;
  155. $read = '';
  156. $tag_uid_a = explode(' ',trim($tag_uid));
  157. $tag = $tag_uid_a[0];
  158. $resultlist = array();
  159. $data = array();
  160. $read = sqimap_fgets($imap_stream);
  161. $i = 0;
  162. while ($read) {
  163. $char = $read{0};
  164. switch ($char)
  165. {
  166. case '+':
  167. default:
  168. $read = sqimap_fgets($imap_stream);
  169. break;
  170. case $tag{0}:
  171. {
  172. /* get the command */
  173. $arg = '';
  174. $i = strlen($tag)+1;
  175. $s = substr($read,$i);
  176. if (($j = strpos($s,' ')) || ($j = strpos($s,"\n"))) {
  177. $arg = substr($s,0,$j);
  178. }
  179. $found_tag = substr($read,0,$i-1);
  180. if ($arg && $found_tag==$tag) {
  181. switch ($arg)
  182. {
  183. case 'OK':
  184. case 'BAD':
  185. case 'NO':
  186. case 'BYE':
  187. case 'PREAUTH':
  188. $response = $arg;
  189. $message = trim(substr($read,$i+strlen($arg)));
  190. break 3; /* switch switch while */
  191. default:
  192. /* this shouldn't happen */
  193. $response = $arg;
  194. $message = trim(substr($read,$i+strlen($arg)));
  195. break 3; /* switch switch while */
  196. }
  197. } elseif($found_tag !== $tag) {
  198. /* reset data array because we do not need this reponse */
  199. $data = array();
  200. $read = sqimap_fgets($imap_stream);
  201. break;
  202. }
  203. } // end case $tag{0}
  204. case '*':
  205. {
  206. if (preg_match('/^\*\s\d+\sFETCH/',$read)) {
  207. /* check for literal */
  208. $s = substr($read,-3);
  209. $fetch_data = array();
  210. do { /* outer loop, continue until next untagged fetch
  211. or tagged reponse */
  212. do { /* innerloop for fetching literals. with this loop
  213. we prohibid that literal responses appear in the
  214. outer loop so we can trust the untagged and
  215. tagged info provided by $read */
  216. if ($s === "}\r\n") {
  217. $j = strrpos($read,'{');
  218. $iLit = substr($read,$j+1,-3);
  219. $fetch_data[] = $read;
  220. $sLiteral = sqimap_fread($imap_stream,$iLit,$filter,$outputstream,$no_return);
  221. if ($sLiteral === false) { /* error */
  222. break 4; /* while while switch while */
  223. }
  224. /* backwards compattibility */
  225. $aLiteral = explode("\n", $sLiteral);
  226. /* release not neaded data */
  227. unset($sLiteral);
  228. foreach ($aLiteral as $line) {
  229. $fetch_data[] = $line ."\n";
  230. }
  231. /* release not neaded data */
  232. unset($aLiteral);
  233. /* next fgets belongs to this fetch because
  234. we just got the exact literalsize and there
  235. must follow data to complete the response */
  236. $read = sqimap_fgets($imap_stream);
  237. if ($read === false) { /* error */
  238. break 4; /* while while switch while */
  239. }
  240. $fetch_data[] = $read;
  241. } else {
  242. $fetch_data[] = $read;
  243. }
  244. /* retrieve next line and check in the while
  245. statements if it belongs to this fetch response */
  246. $read = sqimap_fgets($imap_stream);
  247. if ($read === false) { /* error */
  248. break 4; /* while while switch while */
  249. }
  250. /* check for next untagged reponse and break */
  251. if ($read{0} == '*') break 2;
  252. $s = substr($read,-3);
  253. } while ($s === "}\r\n");
  254. $s = substr($read,-3);
  255. } while ($read{0} !== '*' &&
  256. substr($read,0,strlen($tag)) !== $tag);
  257. $resultlist[] = $fetch_data;
  258. /* release not neaded data */
  259. unset ($fetch_data);
  260. } else {
  261. $s = substr($read,-3);
  262. do {
  263. if ($s === "}\r\n") {
  264. $j = strrpos($read,'{');
  265. $iLit = substr($read,$j+1,-3);
  266. $data[] = $read;
  267. $sLiteral = fread($imap_stream,$iLit);
  268. if ($sLiteral === false) { /* error */
  269. $read = false;
  270. break 3; /* while switch while */
  271. }
  272. $data[] = $sLiteral;
  273. $data[] = sqimap_fgets($imap_stream);
  274. } else {
  275. $data[] = $read;
  276. }
  277. $read = sqimap_fgets($imap_stream);
  278. if ($read === false) {
  279. break 3; /* while switch while */
  280. } else if ($read{0} == '*') {
  281. break;
  282. }
  283. $s = substr($read,-3);
  284. } while ($s === "}\r\n");
  285. break 1;
  286. }
  287. break;
  288. } // end case '*'
  289. } // end switch
  290. } // end while
  291. /* error processing in case $read is false */
  292. if ($read === false) {
  293. unset($data);
  294. set_up_language($squirrelmail_language);
  295. require_once(SM_PATH . 'functions/display_messages.php');
  296. $string = "<b><font color=\"$color[2]\">\n" .
  297. _("ERROR: Connection dropped by IMAP server.") .
  298. "</b><br />\n";
  299. $cmd = explode(' ',$query);
  300. $cmd = strtolower($cmd[0]);
  301. if ($query != '' && $cmd != 'login') {
  302. $string .= ("Query:") . ' '. htmlspecialchars($query)
  303. . '<br />' . "</font><br />\n";
  304. }
  305. error_box($string,$color);
  306. exit;
  307. }
  308. /* Set $resultlist array */
  309. if (!empty($data)) {
  310. $resultlist[] = $data;
  311. }
  312. elseif (empty($resultlist)) {
  313. $resultlist[] = array();
  314. }
  315. /* Return result or handle errors */
  316. if ($handle_errors == false) {
  317. return( $resultlist );
  318. }
  319. switch ($response) {
  320. case 'OK':
  321. return $resultlist;
  322. break;
  323. case 'NO':
  324. /* ignore this error from M$ exchange, it is not fatal (aka bug) */
  325. if (strstr($message, 'command resulted in') === false) {
  326. set_up_language($squirrelmail_language);
  327. require_once(SM_PATH . 'functions/display_messages.php');
  328. $string = "<b><font color=\"$color[2]\">\n" .
  329. _("ERROR: Could not complete request.") .
  330. "</b><br />\n" .
  331. _("Query:") . ' ' .
  332. htmlspecialchars($query) . '<br />' .
  333. _("Reason Given:") . ' ' .
  334. htmlspecialchars($message) . "</font><br />\n";
  335. error_box($string,$color);
  336. echo '</body></html>';
  337. exit;
  338. }
  339. break;
  340. case 'BAD':
  341. set_up_language($squirrelmail_language);
  342. require_once(SM_PATH . 'functions/display_messages.php');
  343. $string = "<b><font color=\"$color[2]\">\n" .
  344. _("ERROR: Bad or malformed request.") .
  345. "</b><br />\n" .
  346. _("Query:") . ' '.
  347. htmlspecialchars($query) . '<br />' .
  348. _("Server responded:") . ' ' .
  349. htmlspecialchars($message) . "</font><br />\n";
  350. error_box($string,$color);
  351. echo '</body></html>';
  352. exit;
  353. case 'BYE':
  354. set_up_language($squirrelmail_language);
  355. require_once(SM_PATH . 'functions/display_messages.php');
  356. $string = "<b><font color=\"$color[2]\">\n" .
  357. _("ERROR: IMAP server closed the connection.") .
  358. "</b><br />\n" .
  359. _("Query:") . ' '.
  360. htmlspecialchars($query) . '<br />' .
  361. _("Server responded:") . ' ' .
  362. htmlspecialchars($message) . "</font><br />\n";
  363. error_box($string,$color);
  364. echo '</body></html>';
  365. exit;
  366. default:
  367. set_up_language($squirrelmail_language);
  368. require_once(SM_PATH . 'functions/display_messages.php');
  369. $string = "<b><font color=\"$color[2]\">\n" .
  370. _("ERROR: Unknown IMAP response.") .
  371. "</b><br />\n" .
  372. _("Query:") . ' '.
  373. htmlspecialchars($query) . '<br />' .
  374. _("Server responded:") . ' ' .
  375. htmlspecialchars($message) . "</font><br />\n";
  376. error_box($string,$color);
  377. /* the error is displayed but because we don't know the reponse we
  378. return the result anyway */
  379. return $resultlist;
  380. break;
  381. }
  382. }
  383. function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors,
  384. &$response, &$message, $query = '',
  385. $filter=false,$outputstream=false,$no_return=false) {
  386. $res = sqimap_read_data_list($imap_stream, $tag_uid, $handle_errors,
  387. $response, $message, $query,$filter,$outputstream,$no_return);
  388. /* sqimap_read_data should be called for one response
  389. but since it just calls sqimap_read_data_list which
  390. handles multiple responses we need to check for that
  391. and merge the $res array IF they are seperated and
  392. IF it was a FETCH response. */
  393. // if (isset($res[1]) && is_array($res[1]) && isset($res[1][0])
  394. // && preg_match('/^\* \d+ FETCH/', $res[1][0])) {
  395. // $result = array();
  396. // foreach($res as $index=>$value) {
  397. // $result = array_merge($result, $res["$index"]);
  398. // }
  399. // }
  400. return $res[0];
  401. }
  402. /**
  403. * Logs the user into the IMAP server. If $hide is set, no error messages
  404. * will be displayed. This function returns the IMAP connection handle.
  405. */
  406. function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
  407. global $color, $squirrelmail_language, $onetimepad, $use_imap_tls, $imap_auth_mech;
  408. if (!isset($onetimepad) || empty($onetimepad)) {
  409. sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION );
  410. }
  411. $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
  412. $host=$imap_server_address;
  413. if (($use_imap_tls == true) and (check_php_version(4,3)) and (extension_loaded('openssl'))) {
  414. /* Use TLS by prefixing "tls://" to the hostname */
  415. $imap_server_address = 'tls://' . $imap_server_address;
  416. }
  417. $imap_stream = @fsockopen($imap_server_address, $imap_port, $error_number, $error_string, 15);
  418. /* Do some error correction */
  419. if (!$imap_stream) {
  420. if (!$hide) {
  421. set_up_language($squirrelmail_language, true);
  422. require_once(SM_PATH . 'functions/display_messages.php');
  423. logout_error( sprintf(_("Error connecting to IMAP server: %s."), $imap_server_address).
  424. "<br />\r\n$error_number : $error_string<br />\r\n",
  425. sprintf(_("Error connecting to IMAP server: %s."), $imap_server_address) );
  426. }
  427. exit;
  428. }
  429. $server_info = fgets ($imap_stream, 1024);
  430. /* Decrypt the password */
  431. $password = OneTimePadDecrypt($password, $onetimepad);
  432. if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
  433. // We're using some sort of authentication OTHER than plain or login
  434. $tag=sqimap_session_id(false);
  435. if ($imap_auth_mech == 'digest-md5') {
  436. $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
  437. } elseif ($imap_auth_mech == 'cram-md5') {
  438. $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
  439. }
  440. fputs($imap_stream,$query);
  441. $answer=sqimap_fgets($imap_stream);
  442. // Trim the "+ " off the front
  443. $response=explode(" ",$answer,3);
  444. if ($response[0] == '+') {
  445. // Got a challenge back
  446. $challenge=$response[1];
  447. if ($imap_auth_mech == 'digest-md5') {
  448. $reply = digest_md5_response($username,$password,$challenge,'imap',$host);
  449. } elseif ($imap_auth_mech == 'cram-md5') {
  450. $reply = cram_md5_response($username,$password,$challenge);
  451. }
  452. fputs($imap_stream,$reply);
  453. $read=sqimap_fgets($imap_stream);
  454. if ($imap_auth_mech == 'digest-md5') {
  455. // DIGEST-MD5 has an extra step..
  456. if (substr($read,0,1) == '+') { // OK so far..
  457. fputs($imap_stream,"\r\n");
  458. $read=sqimap_fgets($imap_stream);
  459. }
  460. }
  461. $results=explode(" ",$read,3);
  462. $response=$results[1];
  463. $message=$results[2];
  464. } else {
  465. // Fake the response, so the error trap at the bottom will work
  466. $response="BAD";
  467. $message='IMAP server does not appear to support the authentication method selected.';
  468. $message .= ' Please contact your system administrator.';
  469. }
  470. } elseif ($imap_auth_mech == 'login') {
  471. // this is a workaround to alert users of LOGINDISABLED, which is done "right" in
  472. // devel but requires functions not available in stable. RFC requires us to
  473. // not send LOGIN when LOGINDISABLED is advertised.
  474. if(stristr($server_info, 'LOGINDISABLED')) {
  475. $response = 'BAD';
  476. $message = _("The IMAP server is reporting that plain text logins are disabled.").' '.
  477. _("Using CRAM-MD5 or DIGEST-MD5 authentication instead may work.").' ';
  478. if (!$use_imap_tls) {
  479. $message .= _("Also, the use of TLS may allow SquirrelMail to login.").' ';
  480. }
  481. $message .= _("Please contact your system administrator and report this error.");
  482. } else {
  483. // Original IMAP login code
  484. $query = 'LOGIN';
  485. if(sq_is8bit($username)) {
  486. $query .= ' {' . strlen($username) . "}\r\n$username";
  487. } else {
  488. $query .= ' "' . quoteimap($username) . '"';
  489. }
  490. if(sq_is8bit($password)) {
  491. $query .= ' {' . strlen($password) . "}\r\n$password";
  492. } else {
  493. $query .= ' "' . quoteimap($password) . '"';
  494. }
  495. $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
  496. }
  497. } elseif ($imap_auth_mech == 'plain') {
  498. /* Replace this with SASL PLAIN if it ever gets implemented */
  499. $response="BAD";
  500. $message='SquirrelMail does not support SASL PLAIN yet. Rerun conf.pl and use login instead.';
  501. } else {
  502. $response="BAD";
  503. $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
  504. }
  505. /* If the connection was not successful, lets see why */
  506. if ($response != 'OK') {
  507. if (!$hide) {
  508. if ($response != 'NO') {
  509. /* "BAD" and anything else gets reported here. */
  510. $message = htmlspecialchars($message);
  511. set_up_language($squirrelmail_language, true);
  512. require_once(SM_PATH . 'functions/display_messages.php');
  513. if ($response == 'BAD') {
  514. $string = sprintf (_("Bad request: %s")."<br />\r\n", $message);
  515. } else {
  516. $string = sprintf (_("Unknown error: %s") . "<br />\n", $message);
  517. }
  518. if (isset($read) && is_array($read)) {
  519. $string .= '<br />' . _("Read data:") . "<br />\n";
  520. foreach ($read as $line) {
  521. $string .= htmlspecialchars($line) . "<br />\n";
  522. }
  523. }
  524. error_box($string,$color);
  525. exit;
  526. } else {
  527. /*
  528. * If the user does not log in with the correct
  529. * username and password it is not possible to get the
  530. * correct locale from the user's preferences.
  531. * Therefore, apply the same hack as on the login
  532. * screen.
  533. *
  534. * $squirrelmail_language is set by a cookie when
  535. * the user selects language and logs out
  536. */
  537. set_up_language($squirrelmail_language, true);
  538. include_once(SM_PATH . 'functions/display_messages.php' );
  539. sqsession_destroy();
  540. /* terminate the session nicely */
  541. sqimap_logout($imap_stream);
  542. logout_error( _("Unknown user or password incorrect.") );
  543. exit;
  544. }
  545. } else {
  546. exit;
  547. }
  548. }
  549. return $imap_stream;
  550. }
  551. /**
  552. * Simply logs out the IMAP session
  553. * @param stream imap_stream the IMAP connection to log out.
  554. * @return void
  555. */
  556. function sqimap_logout ($imap_stream) {
  557. /* Logout is not valid until the server returns 'BYE'
  558. * If we don't have an imap_stream we're already logged out */
  559. if(isset($imap_stream) && $imap_stream)
  560. sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
  561. }
  562. /**
  563. * Retreive the CAPABILITY string from the IMAP server.
  564. * If capability is set, returns only that specific capability,
  565. * else returns array of all capabilities.
  566. */
  567. function sqimap_capability($imap_stream, $capability='') {
  568. global $sqimap_capabilities;
  569. if (!is_array($sqimap_capabilities)) {
  570. $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
  571. $c = explode(' ', $read[0]);
  572. for ($i=2; $i < count($c); $i++) {
  573. $cap_list = explode('=', $c[$i]);
  574. if (isset($cap_list[1])) {
  575. // FIX ME. capabilities can occure multiple times.
  576. // THREAD=REFERENCES THREAD=ORDEREDSUBJECT
  577. $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
  578. } else {
  579. $sqimap_capabilities[$cap_list[0]] = TRUE;
  580. }
  581. }
  582. }
  583. if ($capability) {
  584. if (isset($sqimap_capabilities[$capability])) {
  585. return $sqimap_capabilities[$capability];
  586. } else {
  587. return false;
  588. }
  589. }
  590. return $sqimap_capabilities;
  591. }
  592. /**
  593. * Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test
  594. */
  595. function sqimap_get_delimiter ($imap_stream = false) {
  596. global $sqimap_delimiter, $optional_delimiter;
  597. /* Use configured delimiter if set */
  598. if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
  599. return $optional_delimiter;
  600. }
  601. /* Do some caching here */
  602. if (!$sqimap_delimiter) {
  603. if (sqimap_capability($imap_stream, 'NAMESPACE')) {
  604. /*
  605. * According to something that I can't find, this is supposed to work on all systems
  606. * OS: This won't work in Courier IMAP.
  607. * OS: According to rfc2342 response from NAMESPACE command is:
  608. * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
  609. * OS: We want to lookup all personal NAMESPACES...
  610. */
  611. $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
  612. if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
  613. if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
  614. $pn = $data2[1];
  615. }
  616. $pna = explode(')(', $pn);
  617. while (list($k, $v) = each($pna)) {
  618. $lst = explode('"', $v);
  619. if (isset($lst[3])) {
  620. $pn[$lst[1]] = $lst[3];
  621. } else {
  622. $pn[$lst[1]] = '';
  623. }
  624. }
  625. }
  626. $sqimap_delimiter = $pn[0];
  627. } else {
  628. fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
  629. $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
  630. $quote_position = strpos ($read[0], '"');
  631. $sqimap_delimiter = substr ($read[0], $quote_position+1, 1);
  632. }
  633. }
  634. return $sqimap_delimiter;
  635. }
  636. /**
  637. * Gets the number of messages in the current mailbox.
  638. */
  639. function sqimap_get_num_messages ($imap_stream, $mailbox) {
  640. $read_ary = sqimap_run_command ($imap_stream, "EXAMINE \"$mailbox\"", false, $result, $message);
  641. for ($i = 0; $i < count($read_ary); $i++) {
  642. if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
  643. return $regs[1];
  644. }
  645. }
  646. return false; //"BUG! Couldn't get number of messages in $mailbox!";
  647. }
  648. function parseAddress($address, $max=0) {
  649. $aTokens = array();
  650. $aAddress = array();
  651. $iCnt = strlen($address);
  652. $aSpecials = array('(' ,'<' ,',' ,';' ,':');
  653. $aReplace = array(' (',' <',' ,',' ;',' :');
  654. $address = str_replace($aSpecials,$aReplace,$address);
  655. $i = 0;
  656. while ($i < $iCnt) {
  657. $cChar = $address{$i};
  658. switch($cChar)
  659. {
  660. case '<':
  661. $iEnd = strpos($address,'>',$i+1);
  662. if (!$iEnd) {
  663. $sToken = substr($address,$i);
  664. $i = $iCnt;
  665. } else {
  666. $sToken = substr($address,$i,$iEnd - $i +1);
  667. $i = $iEnd;
  668. }
  669. $sToken = str_replace($aReplace, $aSpecials,$sToken);
  670. $aTokens[] = $sToken;
  671. break;
  672. case '"':
  673. $iEnd = strpos($address,$cChar,$i+1);
  674. if ($iEnd) {
  675. // skip escaped quotes
  676. $prev_char = $address{$iEnd-1};
  677. while ($prev_char === '\\' && substr($address,$iEnd-2,2) !== '\\\\') {
  678. $iEnd = strpos($address,$cChar,$iEnd+1);
  679. if ($iEnd) {
  680. $prev_char = $address{$iEnd-1};
  681. } else {
  682. $prev_char = false;
  683. }
  684. }
  685. }
  686. if (!$iEnd) {
  687. $sToken = substr($address,$i);
  688. $i = $iCnt;
  689. } else {
  690. // also remove the surrounding quotes
  691. $sToken = substr($address,$i+1,$iEnd - $i -1);
  692. $i = $iEnd;
  693. }
  694. $sToken = str_replace($aReplace, $aSpecials,$sToken);
  695. if ($sToken) $aTokens[] = $sToken;
  696. break;
  697. case '(':
  698. $iEnd = strrpos($address,')');
  699. if (!$iEnd) {
  700. $sToken = substr($address,$i);
  701. $i = $iCnt;
  702. } else {
  703. $sToken = substr($address,$i,$iEnd - $i + 1);
  704. $i = $iEnd;
  705. }
  706. $sToken = str_replace($aReplace, $aSpecials,$sToken);
  707. $aTokens[] = $sToken;
  708. break;
  709. case ',':
  710. case ';':
  711. case ';':
  712. case ' ':
  713. $aTokens[] = $cChar;
  714. break;
  715. default:
  716. $iEnd = strpos($address,' ',$i+1);
  717. if ($iEnd) {
  718. $sToken = trim(substr($address,$i,$iEnd - $i));
  719. $i = $iEnd-1;
  720. } else {
  721. $sToken = trim(substr($address,$i));
  722. $i = $iCnt;
  723. }
  724. if ($sToken) $aTokens[] = $sToken;
  725. }
  726. ++$i;
  727. }
  728. $sPersonal = $sEmail = $sComment = $sGroup = '';
  729. $aStack = $aComment = array();
  730. foreach ($aTokens as $sToken) {
  731. if ($max && $max == count($aAddress)) {
  732. return $aAddress;
  733. }
  734. $cChar = $sToken{0};
  735. switch ($cChar)
  736. {
  737. case '=':
  738. case '"':
  739. case ' ':
  740. $aStack[] = $sToken;
  741. break;
  742. case '(':
  743. $aComment[] = substr($sToken,1,-1);
  744. break;
  745. case ';':
  746. if ($sGroup) {
  747. $sEmail = trim(implode(' ',$aStack));
  748. $aAddress[] = array($sGroup,$sEmail);
  749. $aStack = $aComment = array();
  750. $sGroup = '';
  751. break;
  752. }
  753. case ',':
  754. if (!$sEmail) {
  755. while (count($aStack) && !$sEmail) {
  756. $sEmail = trim(array_pop($aStack));
  757. }
  758. }
  759. if (count($aStack)) {
  760. $sPersonal = trim(implode('',$aStack));
  761. } else {
  762. $sPersonal = '';
  763. }
  764. if (!$sPersonal && count($aComment)) {
  765. $sComment = implode(' ',$aComment);
  766. $sPersonal .= $sComment;
  767. }
  768. $aAddress[] = array($sEmail,$sPersonal);
  769. $sPersonal = $sComment = $sEmail = '';
  770. $aStack = $aComment = array();
  771. break;
  772. case ':':
  773. $sGroup = implode(' ',$aStack); break;
  774. $aStack = array();
  775. break;
  776. case '<':
  777. $sEmail = trim(substr($sToken,1,-1));
  778. break;
  779. case '>':
  780. /* skip */
  781. break;
  782. default: $aStack[] = $sToken; break;
  783. }
  784. }
  785. /* now do the action again for the last address */
  786. if (!$sEmail) {
  787. while (count($aStack) && !$sEmail) {
  788. $sEmail = trim(array_pop($aStack));
  789. }
  790. }
  791. if (count($aStack)) {
  792. $sPersonal = trim(implode('',$aStack));
  793. } else {
  794. $sPersonal = '';
  795. }
  796. if (!$sPersonal && count($aComment)) {
  797. $sComment = implode(' ',$aComment);
  798. $sPersonal .= $sComment;
  799. }
  800. $aAddress[] = array($sEmail,$sPersonal);
  801. return $aAddress;
  802. }
  803. /**
  804. * Returns the number of unseen messages in this folder.
  805. */
  806. function sqimap_unseen_messages ($imap_stream, $mailbox) {
  807. $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (UNSEEN)", false, $result, $message);
  808. $i = 0;
  809. $regs = array(false, false);
  810. while (isset($read_ary[$i])) {
  811. if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
  812. break;
  813. }
  814. $i++;
  815. }
  816. return $regs[1];
  817. }
  818. /**
  819. * Returns the number of unseen/total messages in this folder
  820. */
  821. function sqimap_status_messages ($imap_stream, $mailbox) {
  822. $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (MESSAGES UNSEEN RECENT)", false, $result, $message);
  823. $i = 0;
  824. $messages = $unseen = $recent = false;
  825. $regs = array(false,false);
  826. while (isset($read_ary[$i])) {
  827. if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
  828. $unseen = $regs[1];
  829. }
  830. if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
  831. $messages = $regs[1];
  832. }
  833. if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
  834. $recent = $regs[1];
  835. }
  836. $i++;
  837. }
  838. return array('MESSAGES' => $messages, 'UNSEEN'=>$unseen, 'RECENT' => $recent);
  839. }
  840. /**
  841. * Saves a message to a given folder -- used for saving sent messages
  842. */
  843. function sqimap_append ($imap_stream, $sent_folder, $length) {
  844. fputs ($imap_stream, sqimap_session_id() . " APPEND \"$sent_folder\" (\\Seen) {".$length."}\r\n");
  845. $tmp = fgets ($imap_stream, 1024);
  846. sqimap_append_checkresponse($tmp, $sent_folder);
  847. }
  848. function sqimap_append_done ($imap_stream, $folder='') {
  849. fputs ($imap_stream, "\r\n");
  850. $tmp = fgets ($imap_stream, 1024);
  851. sqimap_append_checkresponse($tmp, $folder);
  852. }
  853. function sqimap_append_checkresponse($response, $folder) {
  854. if (preg_match("/(.*)(BAD|NO)(.*)$/", $response, $regs)) {
  855. global $squirrelmail_language, $color;
  856. set_up_language($squirrelmail_language);
  857. require_once(SM_PATH . 'functions/display_messages.php');
  858. $reason = $regs[3];
  859. if ($regs[2] == 'NO') {
  860. $string = "<b><font color=\"$color[2]\">\n" .
  861. _("ERROR: Could not append message to") ." $folder." .
  862. "</b><br />\n" .
  863. _("Server responded:") . ' ' .
  864. $reason . "<br />\n";
  865. if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
  866. $string .= _("Solution:") . ' ' .
  867. _("Remove unneccessary messages from your folders. Start with your Trash folder.")
  868. ."<br />\n";
  869. }
  870. $string .= "</font>\n";
  871. error_box($string,$color);
  872. } else {
  873. $string = "<b><font color=\"$color[2]\">\n" .
  874. _("ERROR: Bad or malformed request.") .
  875. "</b><br />\n" .
  876. _("Server responded:") . ' ' .
  877. $reason . "</font><br />\n";
  878. error_box($string,$color);
  879. exit;
  880. }
  881. }
  882. }
  883. function sqimap_get_user_server ($imap_server, $username) {
  884. if (substr($imap_server, 0, 4) != "map:") {
  885. return $imap_server;
  886. }
  887. $function = substr($imap_server, 4);
  888. return $function($username);
  889. }
  890. /**
  891. * This is an example that gets IMAP servers from yellowpages (NIS).
  892. * you can simple put map:map_yp_alias in your $imap_server_address
  893. * in config.php use your own function instead map_yp_alias to map your
  894. * LDAP whatever way to find the users IMAP server.
  895. */
  896. function map_yp_alias($username) {
  897. $yp = `ypmatch $username aliases`;
  898. return chop(substr($yp, strlen($username)+1));
  899. }
  900. ?>