PageRenderTime 67ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

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

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