PageRenderTime 52ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/tags/last-head-locales/squirrelmail/functions/imap_general.php

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