PageRenderTime 58ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/tags/rel-1_4_19/functions/imap_general.php

#
PHP | 980 lines | 755 code | 53 blank | 172 comment | 185 complexity | f38f03ef0ffd120987d34a8f44d91f8f 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-2009 The SquirrelMail Project Team
  8. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  9. * @version $Id: imap_general.php 13733 2009-05-21 17:11:04Z 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. $read_literal = false;
  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. $s = substr($read,-3);
  242. $read_literal = true;
  243. continue;
  244. } else {
  245. $fetch_data[] = $read;
  246. }
  247. /* retrieve next line and check in the while
  248. statements if it belongs to this fetch response */
  249. $read = sqimap_fgets($imap_stream);
  250. if ($read === false) { /* error */
  251. break 4; /* while while switch while */
  252. }
  253. /* check for next untagged reponse and break */
  254. if ($read{0} == '*') break 2;
  255. $s = substr($read,-3);
  256. } while ($s === "}\r\n" || $read_literal);
  257. $s = substr($read,-3);
  258. } while ($read{0} !== '*' &&
  259. substr($read,0,strlen($tag)) !== $tag);
  260. $resultlist[] = $fetch_data;
  261. /* release not neaded data */
  262. unset ($fetch_data);
  263. } else {
  264. $s = substr($read,-3);
  265. do {
  266. if ($s === "}\r\n") {
  267. $j = strrpos($read,'{');
  268. $iLit = substr($read,$j+1,-3);
  269. // check for numeric value to avoid that untagged responses like:
  270. // * OK [PARSE] Unexpected characters at end of address: {SET:debug=51}
  271. // will trigger literal fetching ({SET:debug=51} !== int )
  272. if (is_numeric($iLit)) {
  273. $data[] = $read;
  274. $sLiteral = fread($imap_stream,$iLit);
  275. if ($sLiteral === false) { /* error */
  276. $read = false;
  277. break 3; /* while switch while */
  278. }
  279. $data[] = $sLiteral;
  280. $data[] = sqimap_fgets($imap_stream);
  281. } else {
  282. $data[] = $read;
  283. }
  284. } else {
  285. $data[] = $read;
  286. }
  287. $read = sqimap_fgets($imap_stream);
  288. if ($read === false) {
  289. break 3; /* while switch while */
  290. } else if ($read{0} == '*') {
  291. break;
  292. }
  293. $s = substr($read,-3);
  294. } while ($s === "}\r\n");
  295. break 1;
  296. }
  297. break;
  298. } // end case '*'
  299. } // end switch
  300. } // end while
  301. /* error processing in case $read is false */
  302. if ($read === false) {
  303. unset($data);
  304. set_up_language($squirrelmail_language);
  305. require_once(SM_PATH . 'functions/display_messages.php');
  306. $string = "<b><font color=\"$color[2]\">\n" .
  307. _("ERROR: Connection dropped by IMAP server.") .
  308. "</b><br />\n";
  309. $cmd = explode(' ',$query);
  310. $cmd = strtolower($cmd[0]);
  311. if ($query != '' && $cmd != 'login') {
  312. $string .= ("Query:") . ' '. htmlspecialchars($query)
  313. . '<br />' . "</font><br />\n";
  314. }
  315. error_box($string,$color);
  316. exit;
  317. }
  318. /* Set $resultlist array */
  319. if (!empty($data)) {
  320. $resultlist[] = $data;
  321. }
  322. elseif (empty($resultlist)) {
  323. $resultlist[] = array();
  324. }
  325. /* Return result or handle errors */
  326. if ($handle_errors == false) {
  327. return( $resultlist );
  328. }
  329. switch ($response) {
  330. case 'OK':
  331. return $resultlist;
  332. break;
  333. case 'NO':
  334. /* ignore this error from M$ exchange, it is not fatal (aka bug) */
  335. if (strstr($message, 'command resulted in') === false) {
  336. set_up_language($squirrelmail_language);
  337. require_once(SM_PATH . 'functions/display_messages.php');
  338. $string = "<b><font color=\"$color[2]\">\n" .
  339. _("ERROR: Could not complete request.") .
  340. "</b><br />\n" .
  341. _("Query:") . ' ' .
  342. htmlspecialchars($query) . '<br />' .
  343. _("Reason Given:") . ' ' .
  344. htmlspecialchars($message) . "</font><br />\n";
  345. error_box($string,$color);
  346. echo '</body></html>';
  347. exit;
  348. }
  349. break;
  350. case 'BAD':
  351. set_up_language($squirrelmail_language);
  352. require_once(SM_PATH . 'functions/display_messages.php');
  353. $string = "<b><font color=\"$color[2]\">\n" .
  354. _("ERROR: Bad or malformed request.") .
  355. "</b><br />\n" .
  356. _("Query:") . ' '.
  357. htmlspecialchars($query) . '<br />' .
  358. _("Server responded:") . ' ' .
  359. htmlspecialchars($message) . "</font><br />\n";
  360. error_box($string,$color);
  361. echo '</body></html>';
  362. exit;
  363. case 'BYE':
  364. set_up_language($squirrelmail_language);
  365. require_once(SM_PATH . 'functions/display_messages.php');
  366. $string = "<b><font color=\"$color[2]\">\n" .
  367. _("ERROR: IMAP server closed the connection.") .
  368. "</b><br />\n" .
  369. _("Query:") . ' '.
  370. htmlspecialchars($query) . '<br />' .
  371. _("Server responded:") . ' ' .
  372. htmlspecialchars($message) . "</font><br />\n";
  373. error_box($string,$color);
  374. echo '</body></html>';
  375. exit;
  376. default:
  377. set_up_language($squirrelmail_language);
  378. require_once(SM_PATH . 'functions/display_messages.php');
  379. $string = "<b><font color=\"$color[2]\">\n" .
  380. _("ERROR: Unknown IMAP response.") .
  381. "</b><br />\n" .
  382. _("Query:") . ' '.
  383. htmlspecialchars($query) . '<br />' .
  384. _("Server responded:") . ' ' .
  385. htmlspecialchars($message) . "</font><br />\n";
  386. error_box($string,$color);
  387. /* the error is displayed but because we don't know the reponse we
  388. return the result anyway */
  389. return $resultlist;
  390. break;
  391. }
  392. }
  393. function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors,
  394. &$response, &$message, $query = '',
  395. $filter=false,$outputstream=false,$no_return=false) {
  396. $res = sqimap_read_data_list($imap_stream, $tag_uid, $handle_errors,
  397. $response, $message, $query,$filter,$outputstream,$no_return);
  398. /* sqimap_read_data should be called for one response
  399. but since it just calls sqimap_read_data_list which
  400. handles multiple responses we need to check for that
  401. and merge the $res array IF they are seperated and
  402. IF it was a FETCH response. */
  403. // if (isset($res[1]) && is_array($res[1]) && isset($res[1][0])
  404. // && preg_match('/^\* \d+ FETCH/', $res[1][0])) {
  405. // $result = array();
  406. // foreach($res as $index=>$value) {
  407. // $result = array_merge($result, $res["$index"]);
  408. // }
  409. // }
  410. return $res[0];
  411. }
  412. /**
  413. * Logs the user into the IMAP server. If $hide is set, no error messages
  414. * will be displayed. This function returns the IMAP connection handle.
  415. */
  416. function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
  417. global $color, $squirrelmail_language, $onetimepad, $use_imap_tls, $imap_auth_mech;
  418. if (!isset($onetimepad) || empty($onetimepad)) {
  419. sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION );
  420. }
  421. $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
  422. $host=$imap_server_address;
  423. if (($use_imap_tls == true) and (check_php_version(4,3)) and (extension_loaded('openssl'))) {
  424. /* Use TLS by prefixing "tls://" to the hostname */
  425. $imap_server_address = 'tls://' . $imap_server_address;
  426. }
  427. $imap_stream = @fsockopen($imap_server_address, $imap_port, $error_number, $error_string, 15);
  428. /* Do some error correction */
  429. if (!$imap_stream) {
  430. if (!$hide) {
  431. set_up_language($squirrelmail_language, true);
  432. require_once(SM_PATH . 'functions/display_messages.php');
  433. logout_error( sprintf(_("Error connecting to IMAP server: %s."), $imap_server_address).
  434. "<br />\r\n$error_number : $error_string<br />\r\n",
  435. sprintf(_("Error connecting to IMAP server: %s."), $imap_server_address) );
  436. }
  437. exit;
  438. }
  439. $server_info = fgets ($imap_stream, 1024);
  440. /* Decrypt the password */
  441. $password = OneTimePadDecrypt($password, $onetimepad);
  442. if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
  443. // We're using some sort of authentication OTHER than plain or login
  444. $tag=sqimap_session_id(false);
  445. if ($imap_auth_mech == 'digest-md5') {
  446. $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
  447. } elseif ($imap_auth_mech == 'cram-md5') {
  448. $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
  449. }
  450. fputs($imap_stream,$query);
  451. $answer=sqimap_fgets($imap_stream);
  452. // Trim the "+ " off the front
  453. $response=explode(" ",$answer,3);
  454. if ($response[0] == '+') {
  455. // Got a challenge back
  456. $challenge=$response[1];
  457. if ($imap_auth_mech == 'digest-md5') {
  458. $reply = digest_md5_response($username,$password,$challenge,'imap',$host);
  459. } elseif ($imap_auth_mech == 'cram-md5') {
  460. $reply = cram_md5_response($username,$password,$challenge);
  461. }
  462. fputs($imap_stream,$reply);
  463. $read=sqimap_fgets($imap_stream);
  464. if ($imap_auth_mech == 'digest-md5') {
  465. // DIGEST-MD5 has an extra step..
  466. if (substr($read,0,1) == '+') { // OK so far..
  467. fputs($imap_stream,"\r\n");
  468. $read=sqimap_fgets($imap_stream);
  469. }
  470. }
  471. $results=explode(" ",$read,3);
  472. $response=$results[1];
  473. $message=$results[2];
  474. } else {
  475. // Fake the response, so the error trap at the bottom will work
  476. $response="BAD";
  477. $message='IMAP server does not appear to support the authentication method selected.';
  478. $message .= ' Please contact your system administrator.';
  479. }
  480. } elseif ($imap_auth_mech == 'login') {
  481. // this is a workaround to alert users of LOGINDISABLED, which is done "right" in
  482. // devel but requires functions not available in stable. RFC requires us to
  483. // not send LOGIN when LOGINDISABLED is advertised.
  484. if(stristr($server_info, 'LOGINDISABLED')) {
  485. $response = 'BAD';
  486. $message = _("The IMAP server is reporting that plain text logins are disabled.").' '.
  487. _("Using CRAM-MD5 or DIGEST-MD5 authentication instead may work.").' ';
  488. if (!$use_imap_tls) {
  489. $message .= _("Also, the use of TLS may allow SquirrelMail to login.").' ';
  490. }
  491. $message .= _("Please contact your system administrator and report this error.");
  492. } else {
  493. // Original IMAP login code
  494. $query = 'LOGIN';
  495. if(sq_is8bit($username)) {
  496. $query .= ' {' . strlen($username) . "}\r\n$username";
  497. } else {
  498. $query .= ' "' . quoteimap($username) . '"';
  499. }
  500. if(sq_is8bit($password)) {
  501. $query .= ' {' . strlen($password) . "}\r\n$password";
  502. } else {
  503. $query .= ' "' . quoteimap($password) . '"';
  504. }
  505. $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
  506. }
  507. } elseif ($imap_auth_mech == 'plain') {
  508. /* Replace this with SASL PLAIN if it ever gets implemented */
  509. $response="BAD";
  510. $message='SquirrelMail does not support SASL PLAIN yet. Rerun conf.pl and use login instead.';
  511. } else {
  512. $response="BAD";
  513. $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
  514. }
  515. /* If the connection was not successful, lets see why */
  516. if ($response != 'OK') {
  517. if (!$hide) {
  518. if ($response != 'NO') {
  519. /* "BAD" and anything else gets reported here. */
  520. $message = htmlspecialchars($message);
  521. set_up_language($squirrelmail_language, true);
  522. require_once(SM_PATH . 'functions/display_messages.php');
  523. if ($response == 'BAD') {
  524. $string = sprintf (_("Bad request: %s")."<br />\r\n", $message);
  525. } else {
  526. $string = sprintf (_("Unknown error: %s") . "<br />\n", $message);
  527. }
  528. if (isset($read) && is_array($read)) {
  529. $string .= '<br />' . _("Read data:") . "<br />\n";
  530. foreach ($read as $line) {
  531. $string .= htmlspecialchars($line) . "<br />\n";
  532. }
  533. }
  534. error_box($string,$color);
  535. exit;
  536. } else {
  537. /*
  538. * If the user does not log in with the correct
  539. * username and password it is not possible to get the
  540. * correct locale from the user's preferences.
  541. * Therefore, apply the same hack as on the login
  542. * screen.
  543. *
  544. * $squirrelmail_language is set by a cookie when
  545. * the user selects language and logs out
  546. */
  547. set_up_language($squirrelmail_language, true);
  548. include_once(SM_PATH . 'functions/display_messages.php' );
  549. sqsession_destroy();
  550. /* terminate the session nicely */
  551. sqimap_logout($imap_stream);
  552. logout_error( _("Unknown user or password incorrect.") );
  553. exit;
  554. }
  555. } else {
  556. exit;
  557. }
  558. }
  559. return $imap_stream;
  560. }
  561. /**
  562. * Simply logs out the IMAP session
  563. * @param stream imap_stream the IMAP connection to log out.
  564. * @return void
  565. */
  566. function sqimap_logout ($imap_stream) {
  567. /* Logout is not valid until the server returns 'BYE'
  568. * If we don't have an imap_stream we're already logged out */
  569. if(isset($imap_stream) && $imap_stream)
  570. sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
  571. }
  572. /**
  573. * Retreive the CAPABILITY string from the IMAP server.
  574. * If capability is set, returns only that specific capability,
  575. * else returns array of all capabilities.
  576. */
  577. function sqimap_capability($imap_stream, $capability='') {
  578. global $sqimap_capabilities;
  579. if (!is_array($sqimap_capabilities)) {
  580. $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
  581. $c = explode(' ', $read[0]);
  582. for ($i=2; $i < count($c); $i++) {
  583. $cap_list = explode('=', $c[$i]);
  584. if (isset($cap_list[1])) {
  585. // FIX ME. capabilities can occure multiple times.
  586. // THREAD=REFERENCES THREAD=ORDEREDSUBJECT
  587. $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
  588. } else {
  589. $sqimap_capabilities[$cap_list[0]] = TRUE;
  590. }
  591. }
  592. }
  593. if ($capability) {
  594. if (isset($sqimap_capabilities[$capability])) {
  595. return $sqimap_capabilities[$capability];
  596. } else {
  597. return false;
  598. }
  599. }
  600. return $sqimap_capabilities;
  601. }
  602. /**
  603. * Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test
  604. */
  605. function sqimap_get_delimiter ($imap_stream = false) {
  606. global $sqimap_delimiter, $optional_delimiter;
  607. /* Use configured delimiter if set */
  608. if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
  609. return $optional_delimiter;
  610. }
  611. /* Do some caching here */
  612. if (!$sqimap_delimiter) {
  613. if (sqimap_capability($imap_stream, 'NAMESPACE')) {
  614. /*
  615. * According to something that I can't find, this is supposed to work on all systems
  616. * OS: This won't work in Courier IMAP.
  617. * OS: According to rfc2342 response from NAMESPACE command is:
  618. * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
  619. * OS: We want to lookup all personal NAMESPACES...
  620. */
  621. $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
  622. if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
  623. if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
  624. $pn = $data2[1];
  625. }
  626. $pna = explode(')(', $pn);
  627. while (list($k, $v) = each($pna)) {
  628. $lst = explode('"', $v);
  629. if (isset($lst[3])) {
  630. $pn[$lst[1]] = $lst[3];
  631. } else {
  632. $pn[$lst[1]] = '';
  633. }
  634. }
  635. }
  636. $sqimap_delimiter = $pn[0];
  637. } else {
  638. fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
  639. $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
  640. $quote_position = strpos ($read[0], '"');
  641. $sqimap_delimiter = substr ($read[0], $quote_position+1, 1);
  642. }
  643. }
  644. return $sqimap_delimiter;
  645. }
  646. /**
  647. * Gets the number of messages in the current mailbox.
  648. */
  649. function sqimap_get_num_messages ($imap_stream, $mailbox) {
  650. $read_ary = sqimap_run_command ($imap_stream, "EXAMINE \"$mailbox\"", false, $result, $message);
  651. for ($i = 0; $i < count($read_ary); $i++) {
  652. if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
  653. return $regs[1];
  654. }
  655. }
  656. return false; //"BUG! Couldn't get number of messages in $mailbox!";
  657. }
  658. /**
  659. * Parses an address string.
  660. FIXME: the original author should step up and document this - the following is a guess based on a couple simple tests of *using* the function, not knowing the code inside
  661. *
  662. * @param string $address Generic email address(es) in any format, including
  663. * possible personal information as well as the
  664. * actual address (such as "Jose" <jose@example.org>
  665. * or "Jose" <jose@example.org>, "Keiko" <keiko@example.org>)
  666. * @param int $max The most email addresses to parse out of the given string
  667. *
  668. * @return array An array with one sub-array for each address found in the
  669. * given string. Each sub-array contains two (?) entries, the
  670. * first containing the actual email address, the second
  671. * containing any personal information that was in the address
  672. * string
  673. *
  674. */
  675. function parseAddress($address, $max=0) {
  676. $aTokens = array();
  677. $aAddress = array();
  678. $iCnt = strlen($address);
  679. $aSpecials = array('(' ,'<' ,',' ,';' ,':');
  680. $aReplace = array(' (',' <',' ,',' ;',' :');
  681. $address = str_replace($aSpecials,$aReplace,$address);
  682. $i = 0;
  683. while ($i < $iCnt) {
  684. $cChar = $address{$i};
  685. switch($cChar)
  686. {
  687. case '<':
  688. $iEnd = strpos($address,'>',$i+1);
  689. if (!$iEnd) {
  690. $sToken = substr($address,$i);
  691. $i = $iCnt;
  692. } else {
  693. $sToken = substr($address,$i,$iEnd - $i +1);
  694. $i = $iEnd;
  695. }
  696. $sToken = str_replace($aReplace, $aSpecials,$sToken);
  697. $aTokens[] = $sToken;
  698. break;
  699. case '"':
  700. $iEnd = strpos($address,$cChar,$i+1);
  701. if ($iEnd) {
  702. // skip escaped quotes
  703. $prev_char = $address{$iEnd-1};
  704. while ($prev_char === '\\' && substr($address,$iEnd-2,2) !== '\\\\') {
  705. $iEnd = strpos($address,$cChar,$iEnd+1);
  706. if ($iEnd) {
  707. $prev_char = $address{$iEnd-1};
  708. } else {
  709. $prev_char = false;
  710. }
  711. }
  712. }
  713. if (!$iEnd) {
  714. $sToken = substr($address,$i);
  715. $i = $iCnt;
  716. } else {
  717. // also remove the surrounding quotes
  718. $sToken = substr($address,$i+1,$iEnd - $i -1);
  719. $i = $iEnd;
  720. }
  721. $sToken = str_replace($aReplace, $aSpecials,$sToken);
  722. if ($sToken) $aTokens[] = $sToken;
  723. break;
  724. case '(':
  725. $iEnd = strrpos($address,')');
  726. if (!$iEnd || $iEnd < $i) {
  727. $sToken = substr($address,$i);
  728. $i = $iCnt;
  729. } else {
  730. $sToken = substr($address,$i,$iEnd - $i + 1);
  731. $i = $iEnd;
  732. }
  733. $sToken = str_replace($aReplace, $aSpecials,$sToken);
  734. $aTokens[] = $sToken;
  735. break;
  736. case ',':
  737. case ';':
  738. case ';':
  739. case ' ':
  740. $aTokens[] = $cChar;
  741. break;
  742. default:
  743. $iEnd = strpos($address,' ',$i+1);
  744. if ($iEnd) {
  745. $sToken = trim(substr($address,$i,$iEnd - $i));
  746. $i = $iEnd-1;
  747. } else {
  748. $sToken = trim(substr($address,$i));
  749. $i = $iCnt;
  750. }
  751. if ($sToken) $aTokens[] = $sToken;
  752. }
  753. ++$i;
  754. }
  755. $sPersonal = $sEmail = $sComment = $sGroup = '';
  756. $aStack = $aComment = array();
  757. foreach ($aTokens as $sToken) {
  758. if ($max && $max == count($aAddress)) {
  759. return $aAddress;
  760. }
  761. $cChar = $sToken{0};
  762. switch ($cChar)
  763. {
  764. case '=':
  765. case '"':
  766. case ' ':
  767. $aStack[] = $sToken;
  768. break;
  769. case '(':
  770. $aComment[] = substr($sToken,1,-1);
  771. break;
  772. case ';':
  773. if ($sGroup) {
  774. $sEmail = trim(implode(' ',$aStack));
  775. $aAddress[] = array($sGroup,$sEmail);
  776. $aStack = $aComment = array();
  777. $sGroup = '';
  778. break;
  779. }
  780. case ',':
  781. if (!$sEmail) {
  782. while (count($aStack) && !$sEmail) {
  783. $sEmail = trim(array_pop($aStack));
  784. }
  785. }
  786. if (count($aStack)) {
  787. $sPersonal = trim(implode('',$aStack));
  788. } else {
  789. $sPersonal = '';
  790. }
  791. if (!$sPersonal && count($aComment)) {
  792. $sComment = implode(' ',$aComment);
  793. $sPersonal .= $sComment;
  794. }
  795. $aAddress[] = array($sEmail,$sPersonal);
  796. $sPersonal = $sComment = $sEmail = '';
  797. $aStack = $aComment = array();
  798. break;
  799. case ':':
  800. $sGroup = implode(' ',$aStack); break;
  801. $aStack = array();
  802. break;
  803. case '<':
  804. $sEmail = trim(substr($sToken,1,-1));
  805. break;
  806. case '>':
  807. /* skip */
  808. break;
  809. default: $aStack[] = $sToken; break;
  810. }
  811. }
  812. /* now do the action again for the last address */
  813. if (!$sEmail) {
  814. while (count($aStack) && !$sEmail) {
  815. $sEmail = trim(array_pop($aStack));
  816. }
  817. }
  818. if (count($aStack)) {
  819. $sPersonal = trim(implode('',$aStack));
  820. } else {
  821. $sPersonal = '';
  822. }
  823. if (!$sPersonal && count($aComment)) {
  824. $sComment = implode(' ',$aComment);
  825. $sPersonal .= $sComment;
  826. }
  827. $aAddress[] = array($sEmail,$sPersonal);
  828. return $aAddress;
  829. }
  830. /**
  831. * Returns the number of unseen messages in this folder.
  832. */
  833. function sqimap_unseen_messages ($imap_stream, $mailbox) {
  834. $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (UNSEEN)", false, $result, $message);
  835. $i = 0;
  836. $regs = array(false, false);
  837. while (isset($read_ary[$i])) {
  838. if (ereg("UNSEEN ([0-9]+)", $read_ary[$i], $regs)) {
  839. break;
  840. }
  841. $i++;
  842. }
  843. return $regs[1];
  844. }
  845. /**
  846. * Returns the number of unseen/total messages in this folder
  847. */
  848. function sqimap_status_messages ($imap_stream, $mailbox) {
  849. $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (MESSAGES UNSEEN RECENT)", false, $result, $message);
  850. $i = 0;
  851. $messages = $unseen = $recent = false;
  852. $regs = array(false,false);
  853. while (isset($read_ary[$i])) {
  854. if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
  855. $unseen = $regs[1];
  856. }
  857. if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
  858. $messages = $regs[1];
  859. }
  860. if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
  861. $recent = $regs[1];
  862. }
  863. $i++;
  864. }
  865. return array('MESSAGES' => $messages, 'UNSEEN'=>$unseen, 'RECENT' => $recent);
  866. }
  867. /**
  868. * Saves a message to a given folder -- used for saving sent messages
  869. */
  870. function sqimap_append ($imap_stream, $sent_folder, $length) {
  871. fputs ($imap_stream, sqimap_session_id() . " APPEND \"$sent_folder\" (\\Seen) {".$length."}\r\n");
  872. $tmp = fgets ($imap_stream, 1024);
  873. sqimap_append_checkresponse($tmp, $sent_folder);
  874. }
  875. function sqimap_append_done ($imap_stream, $folder='') {
  876. fputs ($imap_stream, "\r\n");
  877. $tmp = fgets ($imap_stream, 1024);
  878. sqimap_append_checkresponse($tmp, $folder);
  879. }
  880. function sqimap_append_checkresponse($response, $folder) {
  881. if (preg_match("/(.*)(BAD|NO)(.*)$/", $response, $regs)) {
  882. global $squirrelmail_language, $color;
  883. set_up_language($squirrelmail_language);
  884. require_once(SM_PATH . 'functions/display_messages.php');
  885. $reason = $regs[3];
  886. if ($regs[2] == 'NO') {
  887. $string = "<b><font color=\"$color[2]\">\n" .
  888. _("ERROR: Could not append message to") ." $folder." .
  889. "</b><br />\n" .
  890. _("Server responded:") . ' ' .
  891. $reason . "<br />\n";
  892. if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
  893. $string .= _("Solution:") . ' ' .
  894. _("Remove unneccessary messages from your folders. Start with your Trash folder.")
  895. ."<br />\n";
  896. }
  897. $string .= "</font>\n";
  898. error_box($string,$color);
  899. } else {
  900. $string = "<b><font color=\"$color[2]\">\n" .
  901. _("ERROR: Bad or malformed request.") .
  902. "</b><br />\n" .
  903. _("Server responded:") . ' ' .
  904. $reason . "</font><br />\n";
  905. error_box($string,$color);
  906. exit;
  907. }
  908. }
  909. }
  910. function sqimap_get_user_server ($imap_server, $username) {
  911. if (substr($imap_server, 0, 4) != "map:") {
  912. return $imap_server;
  913. }
  914. $function = substr($imap_server, 4);
  915. return $function($username);
  916. }
  917. /**
  918. * This is an example that gets IMAP servers from yellowpages (NIS).
  919. * you can simple put map:map_yp_alias in your $imap_server_address
  920. * in config.php use your own function instead map_yp_alias to map your
  921. * LDAP whatever way to find the users IMAP server.
  922. */
  923. function map_yp_alias($username) {
  924. $safe_username = escapeshellarg($username);
  925. $yp = `ypmatch $safe_username aliases`;
  926. return chop(substr($yp, strlen($username)+1));
  927. }