PageRenderTime 56ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/branches/DEVEL_MARC/squirrelmail/functions/imap_general.php

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