PageRenderTime 72ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/branches/SM-1_4-STABLE/squirrelmail/functions/imap_general.php

#
PHP | 1086 lines | 828 code | 65 blank | 193 comment | 202 complexity | 22271d5e949de5a36269e8dc6ba5b5c5 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 1999-2012 The SquirrelMail Project Team
  8. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  9. * @version $Id: imap_general.php 14290 2012-03-24 10:41:19Z 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. 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['commands'][0], 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['commands'][0]);
  78. $i = 0;
  79. $cnt = count($query['literal_args']);
  80. while( $i < $cnt ) {
  81. if (($cnt > 1) && ($i < ($cnt - 1))) {
  82. $command = sprintf("%s%s {%d}\r\n", $query['literal_args'][$i], (!empty($query['commands'][$i+1]) ? ' ' . $query['commands'][$i+1] : ''), 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['commands'][0]);
  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. $sqimap_capabilities;
  454. // Note/TODO: This hack grabs the $authz argument from the session
  455. $authz = '';
  456. global $authz;
  457. sqgetglobalvar('authz' , $authz , SQ_SESSION);
  458. if(!empty($authz)) {
  459. /* authz plugin - specific:
  460. * Get proxy login parameters from authz plugin configuration. If they
  461. * exist, they will override the current ones.
  462. * This is useful if we want to use different SASL authentication mechanism
  463. * and/or different TLS settings for proxy logins. */
  464. global $authz_imap_auth_mech, $authz_use_imap_tls, $authz_imapPort_tls;
  465. $imap_auth_mech = !empty($authz_imap_auth_mech) ? strtolower($authz_imap_auth_mech) : $imap_auth_mech;
  466. $use_imap_tls = !empty($authz_use_imap_tls)? $authz_use_imap_tls : $use_imap_tls;
  467. $imap_port = !empty($authz_use_imap_tls)? $authz_imapPort_tls : $imap_port;
  468. if($imap_auth_mech == 'login' || $imap_auth_mech == 'cram-md5') {
  469. logout_error("Misconfigured Plugin (authz or equivalent):<br/>".
  470. "The LOGIN and CRAM-MD5 authentication mechanisms cannot be used when attempting proxy login.");
  471. exit;
  472. }
  473. }
  474. if (!isset($onetimepad) || empty($onetimepad)) {
  475. sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION );
  476. }
  477. $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
  478. $host=$imap_server_address;
  479. if (($use_imap_tls == true) and (check_php_version(4,3)) and (extension_loaded('openssl'))) {
  480. /* Use TLS by prefixing "tls://" to the hostname */
  481. $imap_server_address = 'tls://' . $imap_server_address;
  482. }
  483. $imap_stream = @fsockopen($imap_server_address, $imap_port, $error_number, $error_string, 15);
  484. /* Do some error correction */
  485. if (!$imap_stream) {
  486. if (!$hide) {
  487. set_up_language($squirrelmail_language, true);
  488. require_once(SM_PATH . 'functions/display_messages.php');
  489. logout_error( sprintf(_("Error connecting to IMAP server: %s."), $imap_server_address).
  490. "<br />\r\n$error_number : $error_string<br />\r\n",
  491. sprintf(_("Error connecting to IMAP server: %s."), $imap_server_address) );
  492. }
  493. exit;
  494. }
  495. $server_info = fgets ($imap_stream, 1024);
  496. /* Decrypt the password */
  497. $password = OneTimePadDecrypt($password, $onetimepad);
  498. if (!isset($sqimap_capabilities)) {
  499. sqgetglobalvar('sqimap_capabilities' , $sqimap_capabilities , SQ_SESSION );
  500. }
  501. if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
  502. // We're using some sort of authentication OTHER than plain or login
  503. $tag=sqimap_session_id(false);
  504. if ($imap_auth_mech == 'digest-md5') {
  505. $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
  506. } elseif ($imap_auth_mech == 'cram-md5') {
  507. $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
  508. }
  509. fputs($imap_stream,$query);
  510. $answer=sqimap_fgets($imap_stream);
  511. // Trim the "+ " off the front
  512. $response=explode(" ",$answer,3);
  513. if ($response[0] == '+') {
  514. // Got a challenge back
  515. $challenge=$response[1];
  516. if ($imap_auth_mech == 'digest-md5') {
  517. $reply = digest_md5_response($username,$password,$challenge,'imap',$host,$authz);
  518. } elseif ($imap_auth_mech == 'cram-md5') {
  519. $reply = cram_md5_response($username,$password,$challenge);
  520. }
  521. fputs($imap_stream,$reply);
  522. $read=sqimap_fgets($imap_stream);
  523. if ($imap_auth_mech == 'digest-md5') {
  524. // DIGEST-MD5 has an extra step..
  525. if (substr($read,0,1) == '+') { // OK so far..
  526. fputs($imap_stream,"\r\n");
  527. $read=sqimap_fgets($imap_stream);
  528. }
  529. }
  530. $results=explode(" ",$read,3);
  531. $response=$results[1];
  532. $message=$results[2];
  533. } else {
  534. // Fake the response, so the error trap at the bottom will work
  535. $response="BAD";
  536. $message='IMAP server does not appear to support the authentication method selected.';
  537. $message .= ' Please contact your system administrator.';
  538. }
  539. } elseif ($imap_auth_mech == 'login') {
  540. // this is a workaround to alert users of LOGINDISABLED, which is done "right" in
  541. // devel but requires functions not available in stable. RFC requires us to
  542. // not send LOGIN when LOGINDISABLED is advertised.
  543. if(stristr($server_info, 'LOGINDISABLED')) {
  544. $response = 'BAD';
  545. $message = _("The IMAP server is reporting that plain text logins are disabled.").' '.
  546. _("Using CRAM-MD5 or DIGEST-MD5 authentication instead may work.").' ';
  547. if (!$use_imap_tls) {
  548. $message .= _("Also, the use of TLS may allow SquirrelMail to login.").' ';
  549. }
  550. $message .= _("Please contact your system administrator and report this error.");
  551. } else {
  552. // Original IMAP login code
  553. if(sq_is8bit($username) || sq_is8bit($password)) {
  554. $query['commands'][0] = 'LOGIN';
  555. $query['literal_args'][0] = $username;
  556. $query['commands'][1] = '';
  557. $query['literal_args'][1] = $password;
  558. $read = sqimap_run_literal_command($imap_stream, $query, false, $response, $message);
  559. } else {
  560. $query = 'LOGIN "' . quoteimap($username) . '"'
  561. . ' "' . quoteimap($password) . '"';
  562. $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
  563. }
  564. }
  565. } elseif ($imap_auth_mech == 'plain') {
  566. /***
  567. * SASL PLAIN, RFC 4616 (updates 2595)
  568. *
  569. * The mechanism consists of a single message, a string of [UTF-8]
  570. * encoded [Unicode] characters, from the client to the server. The
  571. * client presents the authorization identity (identity to act as),
  572. * followed by a NUL (U+0000) character, followed by the authentication
  573. * identity (identity whose password will be used), followed by a NUL
  574. * (U+0000) character, followed by the clear-text password. As with
  575. * other SASL mechanisms, the client does not provide an authorization
  576. * identity when it wishes the server to derive an identity from the
  577. * credentials and use that as the authorization identity.
  578. */
  579. $tag=sqimap_session_id(false);
  580. $sasl = (isset($sqimap_capabilities['SASL-IR']) && $sqimap_capabilities['SASL-IR']) ? true : false;
  581. if(!empty($authz)) {
  582. $auth = base64_encode("$username\0$authz\0$password");
  583. } else {
  584. $auth = base64_encode("$username\0$username\0$password");
  585. }
  586. if ($sasl) {
  587. // IMAP Extension for SASL Initial Client Response
  588. // <draft-siemborski-imap-sasl-initial-response-01b.txt>
  589. $query = $tag . " AUTHENTICATE PLAIN $auth\r\n";
  590. fputs($imap_stream, $query);
  591. $read = sqimap_fgets($imap_stream);
  592. } else {
  593. $query = $tag . " AUTHENTICATE PLAIN\r\n";
  594. fputs($imap_stream, $query);
  595. $read=sqimap_fgets($imap_stream);
  596. if (substr($read,0,1) == '+') { // OK so far..
  597. fputs($imap_stream, "$auth\r\n");
  598. $read = sqimap_fgets($imap_stream);
  599. }
  600. }
  601. $results=explode(" ",$read,3);
  602. $response=$results[1];
  603. $message=$results[2];
  604. } else {
  605. $response="BAD";
  606. $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
  607. }
  608. /* If the connection was not successful, lets see why */
  609. if ($response != 'OK') {
  610. if (!$hide) {
  611. if ($response != 'NO') {
  612. /* "BAD" and anything else gets reported here. */
  613. $message = htmlspecialchars($message);
  614. set_up_language($squirrelmail_language, true);
  615. require_once(SM_PATH . 'functions/display_messages.php');
  616. if ($response == 'BAD') {
  617. $string = sprintf (_("Bad request: %s")."<br />\r\n", $message);
  618. } else {
  619. $string = sprintf (_("Unknown error: %s") . "<br />\n", $message);
  620. }
  621. if (isset($read) && is_array($read)) {
  622. $string .= '<br />' . _("Read data:") . "<br />\n";
  623. foreach ($read as $line) {
  624. $string .= htmlspecialchars($line) . "<br />\n";
  625. }
  626. }
  627. error_box($string,$color);
  628. exit;
  629. } else {
  630. /*
  631. * If the user does not log in with the correct
  632. * username and password it is not possible to get the
  633. * correct locale from the user's preferences.
  634. * Therefore, apply the same hack as on the login
  635. * screen.
  636. *
  637. * $squirrelmail_language is set by a cookie when
  638. * the user selects language and logs out
  639. */
  640. set_up_language($squirrelmail_language, true);
  641. include_once(SM_PATH . 'functions/display_messages.php' );
  642. sqsession_destroy();
  643. /* terminate the session nicely */
  644. sqimap_logout($imap_stream);
  645. logout_error( _("Unknown user or password incorrect.") );
  646. exit;
  647. }
  648. } else {
  649. exit;
  650. }
  651. }
  652. return $imap_stream;
  653. }
  654. /**
  655. * Simply logs out the IMAP session
  656. * @param stream imap_stream the IMAP connection to log out.
  657. * @return void
  658. */
  659. function sqimap_logout ($imap_stream) {
  660. /* Logout is not valid until the server returns 'BYE'
  661. * If we don't have an imap_stream we're already logged out */
  662. if(isset($imap_stream) && $imap_stream)
  663. sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
  664. }
  665. /**
  666. * Retreive the CAPABILITY string from the IMAP server.
  667. * If capability is set, returns only that specific capability,
  668. * else returns array of all capabilities.
  669. */
  670. function sqimap_capability($imap_stream, $capability='') {
  671. global $sqimap_capabilities;
  672. if (!is_array($sqimap_capabilities)) {
  673. $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
  674. $c = explode(' ', $read[0]);
  675. for ($i=2; $i < count($c); $i++) {
  676. $cap_list = explode('=', $c[$i]);
  677. if (isset($cap_list[1])) {
  678. // FIX ME. capabilities can occure multiple times.
  679. // THREAD=REFERENCES THREAD=ORDEREDSUBJECT
  680. $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
  681. } else {
  682. $sqimap_capabilities[$cap_list[0]] = TRUE;
  683. }
  684. }
  685. }
  686. if ($capability) {
  687. if (isset($sqimap_capabilities[$capability])) {
  688. return $sqimap_capabilities[$capability];
  689. } else {
  690. return false;
  691. }
  692. }
  693. return $sqimap_capabilities;
  694. }
  695. /**
  696. * Returns the delimeter between mailboxes: INBOX/Test, or INBOX.Test
  697. */
  698. function sqimap_get_delimiter ($imap_stream = false) {
  699. global $sqimap_delimiter, $optional_delimiter;
  700. /* Use configured delimiter if set */
  701. if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
  702. return $optional_delimiter;
  703. }
  704. /* Do some caching here */
  705. if (!$sqimap_delimiter) {
  706. if (sqimap_capability($imap_stream, 'NAMESPACE')) {
  707. /*
  708. * According to something that I can't find, this is supposed to work on all systems
  709. * OS: This won't work in Courier IMAP.
  710. * OS: According to rfc2342 response from NAMESPACE command is:
  711. * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
  712. * OS: We want to lookup all personal NAMESPACES...
  713. */
  714. $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
  715. if (preg_match('/\* NAMESPACE +(\( *\(.+\) *\)|NIL) +(\( *\(.+\) *\)|NIL) +(\( *\(.+\) *\)|NIL)/i', $read[0], $data)) {
  716. if (preg_match('/^\( *\((.*)\) *\)/', $data[1], $data2)) {
  717. $pn = $data2[1];
  718. $pna = explode(')(', $pn);
  719. $delnew = array();
  720. while (list($k, $v) = each($pna)) {
  721. $lst = explode('"', $v);
  722. if (isset($lst[3])) {
  723. $delnew[$lst[1]] = $lst[3];
  724. } else {
  725. $delnew[$lst[1]] = '';
  726. }
  727. }
  728. $sqimap_delimiter = array_shift($delnew);
  729. }
  730. }
  731. } else {
  732. fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
  733. $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
  734. $quote_position = strpos ($read[0], '"');
  735. $sqimap_delimiter = substr ($read[0], $quote_position+1, 1);
  736. }
  737. }
  738. return $sqimap_delimiter;
  739. }
  740. /**
  741. * Gets the number of messages in the current mailbox.
  742. */
  743. function sqimap_get_num_messages ($imap_stream, $mailbox) {
  744. $read_ary = sqimap_run_command ($imap_stream, "EXAMINE \"$mailbox\"", false, $result, $message);
  745. for ($i = 0; $i < count($read_ary); $i++) {
  746. if (preg_match('/[^ ]+ +([^ ]+) +EXISTS/', $read_ary[$i], $regs)) {
  747. return $regs[1];
  748. }
  749. }
  750. return false; //"BUG! Couldn't get number of messages in $mailbox!";
  751. }
  752. /**
  753. * Parses an address string.
  754. 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
  755. *
  756. * @param string $address Generic email address(es) in any format, including
  757. * possible personal information as well as the
  758. * actual address (such as "Jose" <jose@example.org>
  759. * or "Jose" <jose@example.org>, "Keiko" <keiko@example.org>)
  760. * @param int $max The most email addresses to parse out of the given string
  761. *
  762. * @return array An array with one sub-array for each address found in the
  763. * given string. Each sub-array contains two (?) entries, the
  764. * first containing the actual email address, the second
  765. * containing any personal information that was in the address
  766. * string
  767. *
  768. */
  769. function parseAddress($address, $max=0) {
  770. $aTokens = array();
  771. $aAddress = array();
  772. $iCnt = strlen($address);
  773. $aSpecials = array('(' ,'<' ,',' ,';' ,':');
  774. $aReplace = array(' (',' <',' ,',' ;',' :');
  775. $address = str_replace($aSpecials,$aReplace,$address);
  776. $i = 0;
  777. while ($i < $iCnt) {
  778. $cChar = $address{$i};
  779. switch($cChar)
  780. {
  781. case '<':
  782. $iEnd = strpos($address,'>',$i+1);
  783. if (!$iEnd) {
  784. $sToken = substr($address,$i);
  785. $i = $iCnt;
  786. } else {
  787. $sToken = substr($address,$i,$iEnd - $i +1);
  788. $i = $iEnd;
  789. }
  790. $sToken = str_replace($aReplace, $aSpecials,$sToken);
  791. $aTokens[] = $sToken;
  792. break;
  793. case '"':
  794. $iEnd = strpos($address,$cChar,$i+1);
  795. if ($iEnd) {
  796. // skip escaped quotes
  797. $prev_char = $address{$iEnd-1};
  798. while ($prev_char === '\\' && substr($address,$iEnd-2,2) !== '\\\\') {
  799. $iEnd = strpos($address,$cChar,$iEnd+1);
  800. if ($iEnd) {
  801. $prev_char = $address{$iEnd-1};
  802. } else {
  803. $prev_char = false;
  804. }
  805. }
  806. }
  807. if (!$iEnd) {
  808. $sToken = substr($address,$i);
  809. $i = $iCnt;
  810. } else {
  811. // also remove the surrounding quotes
  812. $sToken = substr($address,$i+1,$iEnd - $i -1);
  813. $i = $iEnd;
  814. }
  815. $sToken = str_replace($aReplace, $aSpecials,$sToken);
  816. if ($sToken) $aTokens[] = $sToken;
  817. break;
  818. case '(':
  819. $iEnd = strrpos($address,')');
  820. if (!$iEnd || $iEnd < $i) {
  821. $sToken = substr($address,$i);
  822. $i = $iCnt;
  823. } else {
  824. $sToken = substr($address,$i,$iEnd - $i + 1);
  825. $i = $iEnd;
  826. }
  827. $sToken = str_replace($aReplace, $aSpecials,$sToken);
  828. $aTokens[] = $sToken;
  829. break;
  830. case ',':
  831. case ';':
  832. case ';':
  833. case ' ':
  834. $aTokens[] = $cChar;
  835. break;
  836. default:
  837. $iEnd = strpos($address,' ',$i+1);
  838. if ($iEnd) {
  839. $sToken = trim(substr($address,$i,$iEnd - $i));
  840. $i = $iEnd-1;
  841. } else {
  842. $sToken = trim(substr($address,$i));
  843. $i = $iCnt;
  844. }
  845. if ($sToken) $aTokens[] = $sToken;
  846. }
  847. ++$i;
  848. }
  849. $sPersonal = $sEmail = $sComment = $sGroup = '';
  850. $aStack = $aComment = array();
  851. foreach ($aTokens as $sToken) {
  852. if ($max && $max == count($aAddress)) {
  853. return $aAddress;
  854. }
  855. $cChar = $sToken{0};
  856. switch ($cChar)
  857. {
  858. case '=':
  859. case '"':
  860. case ' ':
  861. $aStack[] = $sToken;
  862. break;
  863. case '(':
  864. $aComment[] = substr($sToken,1,-1);
  865. break;
  866. case ';':
  867. if ($sGroup) {
  868. $sEmail = trim(implode(' ',$aStack));
  869. $aAddress[] = array($sGroup,$sEmail);
  870. $aStack = $aComment = array();
  871. $sGroup = '';
  872. break;
  873. }
  874. case ',':
  875. if (!$sEmail) {
  876. while (count($aStack) && !$sEmail) {
  877. $sEmail = trim(array_pop($aStack));
  878. }
  879. }
  880. if (count($aStack)) {
  881. $sPersonal = trim(implode('',$aStack));
  882. } else {
  883. $sPersonal = '';
  884. }
  885. if (!$sPersonal && count($aComment)) {
  886. $sComment = implode(' ',$aComment);
  887. $sPersonal .= $sComment;
  888. }
  889. $aAddress[] = array($sEmail,$sPersonal);
  890. $sPersonal = $sComment = $sEmail = '';
  891. $aStack = $aComment = array();
  892. break;
  893. case ':':
  894. $sGroup = implode(' ',$aStack); break;
  895. $aStack = array();
  896. break;
  897. case '<':
  898. $sEmail = trim(substr($sToken,1,-1));
  899. break;
  900. case '>':
  901. /* skip */
  902. break;
  903. default: $aStack[] = $sToken; break;
  904. }
  905. }
  906. /* now do the action again for the last address */
  907. if (!$sEmail) {
  908. while (count($aStack) && !$sEmail) {
  909. $sEmail = trim(array_pop($aStack));
  910. }
  911. }
  912. if (count($aStack)) {
  913. $sPersonal = trim(implode('',$aStack));
  914. } else {
  915. $sPersonal = '';
  916. }
  917. if (!$sPersonal && count($aComment)) {
  918. $sComment = implode(' ',$aComment);
  919. $sPersonal .= $sComment;
  920. }
  921. $aAddress[] = array($sEmail,$sPersonal);
  922. return $aAddress;
  923. }
  924. /**
  925. * Returns the number of unseen messages in this folder.
  926. */
  927. function sqimap_unseen_messages ($imap_stream, $mailbox) {
  928. $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (UNSEEN)", false, $result, $message);
  929. $i = 0;
  930. $regs = array(false, false);
  931. while (isset($read_ary[$i])) {
  932. if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
  933. break;
  934. }
  935. $i++;
  936. }
  937. return $regs[1];
  938. }
  939. /**
  940. * Returns the number of unseen/total messages in this folder
  941. */
  942. function sqimap_status_messages ($imap_stream, $mailbox) {
  943. $read_ary = sqimap_run_command ($imap_stream, "STATUS \"$mailbox\" (MESSAGES UNSEEN RECENT)", false, $result, $message);
  944. $i = 0;
  945. $messages = $unseen = $recent = false;
  946. $regs = array(false,false);
  947. while (isset($read_ary[$i])) {
  948. if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
  949. $unseen = $regs[1];
  950. }
  951. if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
  952. $messages = $regs[1];
  953. }
  954. if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
  955. $recent = $regs[1];
  956. }
  957. $i++;
  958. }
  959. return array('MESSAGES' => $messages, 'UNSEEN'=>$unseen, 'RECENT' => $recent);
  960. }
  961. /**
  962. * Saves a message to a given folder -- used for saving sent messages
  963. */
  964. function sqimap_append ($imap_stream, $sent_folder, $length) {
  965. fputs ($imap_stream, sqimap_session_id() . " APPEND \"$sent_folder\" (\\Seen) {".$length."}\r\n");
  966. $tmp = fgets ($imap_stream, 1024);
  967. sqimap_append_checkresponse($tmp, $sent_folder);
  968. }
  969. function sqimap_append_done ($imap_stream, $folder='') {
  970. fputs ($imap_stream, "\r\n");
  971. $tmp = fgets ($imap_stream, 1024);
  972. sqimap_append_checkresponse($tmp, $folder);
  973. }
  974. function sqimap_append_checkresponse($response, $folder) {
  975. if (preg_match("/(.*)(BAD|NO)(.*)$/", $response, $regs)) {
  976. global $squirrelmail_language, $color;
  977. set_up_language($squirrelmail_language);
  978. require_once(SM_PATH . 'functions/display_messages.php');
  979. $reason = $regs[3];
  980. if ($regs[2] == 'NO') {
  981. $string = "<b><font color=\"$color[2]\">\n" .
  982. _("ERROR: Could not append message to") ." $folder." .
  983. "</b><br />\n" .
  984. _("Server responded:") . ' ' .
  985. $reason . "<br />\n";
  986. if (preg_match("/(.*)(quota)(.*)$/i", $reason, $regs)) {
  987. $string .= _("Solution:") . ' ' .
  988. _("Remove unneccessary messages from your folders. Start with your Trash folder.")
  989. ."<br />\n";
  990. }
  991. $string .= "</font>\n";
  992. error_box($string,$color);
  993. } else {
  994. $string = "<b><font color=\"$color[2]\">\n" .
  995. _("ERROR: Bad or malformed request.") .
  996. "</b><br />\n" .
  997. _("Server responded:") . ' ' .
  998. $reason . "</font><br />\n";
  999. error_box($string,$color);
  1000. exit;
  1001. }
  1002. }
  1003. }
  1004. function sqimap_get_user_server ($imap_server, $username) {
  1005. if (substr($imap_server, 0, 4) != "map:") {
  1006. return $imap_server;
  1007. }
  1008. $function = substr($imap_server, 4);
  1009. return $function($username);
  1010. }
  1011. /**
  1012. * This is an example that gets IMAP servers from yellowpages (NIS).
  1013. * you can simple put map:map_yp_alias in your $imap_server_address
  1014. * in config.php use your own function instead map_yp_alias to map your
  1015. * LDAP whatever way to find the users IMAP server.
  1016. */
  1017. function map_yp_alias($username) {
  1018. $safe_username = escapeshellarg($username);
  1019. $yp = `ypmatch $safe_username aliases`;
  1020. return chop(substr($yp, strlen($username)+1));
  1021. }