PageRenderTime 49ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/tags/rel_1_4_5-rc1/squirrelmail/functions/imap_general.php

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