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

/tags/rel-1_4_4-rc1/squirrelmail/functions/imap_general.php

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