PageRenderTime 54ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

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

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