PageRenderTime 53ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/tags/rel-1_5_0/squirrelmail/functions/imap_general.php

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