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

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

#
PHP | 1294 lines | 922 code | 61 blank | 311 comment | 180 complexity | f6b436ed4cb3f77754432477327bfa75 MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * imap_general.php
  4. *
  5. * This implements all functions that do general IMAP functions.
  6. *
  7. * @copyright &copy; 1999-2006 The SquirrelMail Project Team
  8. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  9. * @version $Id: imap_general.php 10706 2006-02-11 15:20:06Z stekkel $
  10. * @package squirrelmail
  11. * @subpackage imap
  12. */
  13. /** Includes.. */
  14. require_once(SM_PATH . 'functions/page_header.php');
  15. require_once(SM_PATH . 'functions/auth.php');
  16. include_once(SM_PATH . 'functions/rfc822address.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 (since 1.3.0) controls use of unique
  21. * identifiers/message sequence numbers in IMAP commands. See IMAP
  22. * rfc 'UID command' chapter.
  23. * @return string IMAP session id of the form 'A000'.
  24. * @since 1.2.0
  25. */
  26. function sqimap_session_id($unique_id = FALSE) {
  27. static $sqimap_session_id = 1;
  28. if (!$unique_id) {
  29. return( sprintf("A%03d", $sqimap_session_id++) );
  30. } else {
  31. return( sprintf("A%03d", $sqimap_session_id++) . ' UID' );
  32. }
  33. }
  34. /**
  35. * Both send a command and accept the result from the command.
  36. * This is to allow proper session number handling.
  37. * @param stream $imap_stream imap connection resource
  38. * @param string $query imap command
  39. * @param boolean $handle_errors see sqimap_retrieve_imap_response()
  40. * @param array $response
  41. * @param array $message
  42. * @param boolean $unique_id (since 1.3.0) see sqimap_session_id().
  43. * @return mixed returns false on imap error. displays error message
  44. * if imap stream is not available.
  45. * @since 1.2.3
  46. */
  47. function sqimap_run_command_list ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
  48. if ($imap_stream) {
  49. $sid = sqimap_session_id($unique_id);
  50. fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
  51. $tag_uid_a = explode(' ',trim($sid));
  52. $tag = $tag_uid_a[0];
  53. $read = sqimap_retrieve_imap_response ($imap_stream, $tag, $handle_errors, $response, $message, $query );
  54. /* get the response and the message */
  55. $message = $message[$tag];
  56. $response = $response[$tag];
  57. return $read[$tag];
  58. } else {
  59. global $squirrelmail_language, $color;
  60. set_up_language($squirrelmail_language);
  61. require_once(SM_PATH . 'functions/display_messages.php');
  62. $string = "<b><font color=\"$color[2]\">\n" .
  63. _("ERROR: No available IMAP stream.") .
  64. "</b></font>\n";
  65. error_box($string,$color);
  66. return false;
  67. }
  68. }
  69. /**
  70. * @param stream $imap_stream imap connection resource
  71. * @param string $query imap command
  72. * @param boolean $handle_errors see sqimap_retrieve_imap_response()
  73. * @param array $response empty string, if return = false
  74. * @param array $message empty string, if return = false
  75. * @param boolean $unique_id (since 1.3.0) see sqimap_session_id()
  76. * @param boolean $filter (since 1.4.1 and 1.5.0) see sqimap_fread()
  77. * @param mixed $outputstream (since 1.4.1 and 1.5.0) see sqimap_fread()
  78. * @param boolean $no_return (since 1.4.1 and 1.5.0) see sqimap_fread()
  79. * @return mixed returns false on imap error. displays error message
  80. * if imap stream is not available.
  81. * @since 1.2.3
  82. */
  83. function sqimap_run_command ($imap_stream, $query, $handle_errors, &$response,
  84. &$message, $unique_id = false,$filter=false,
  85. $outputstream=false,$no_return=false) {
  86. if ($imap_stream) {
  87. $sid = sqimap_session_id($unique_id);
  88. fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
  89. $tag_uid_a = explode(' ',trim($sid));
  90. $tag = $tag_uid_a[0];
  91. $read = sqimap_read_data ($imap_stream, $tag, $handle_errors, $response,
  92. $message, $query,$filter,$outputstream,$no_return);
  93. if (empty($read)) { //IMAP server dropped its connection
  94. $response = '';
  95. $message = '';
  96. return false;
  97. }
  98. /* retrieve the response and the message */
  99. $response = $response[$tag];
  100. $message = $message[$tag];
  101. if (!empty($read[$tag])) {
  102. return $read[$tag][0];
  103. } else {
  104. return $read[$tag];
  105. }
  106. } else {
  107. global $squirrelmail_language, $color;
  108. set_up_language($squirrelmail_language);
  109. require_once(SM_PATH . 'functions/display_messages.php');
  110. $string = "<b><font color=\"$color[2]\">\n" .
  111. _("ERROR: No available IMAP stream.") .
  112. "</b></font>\n";
  113. error_box($string,$color);
  114. return false;
  115. }
  116. }
  117. /**
  118. * @param mixed $new_query
  119. * @param string $tag
  120. * @param array $aQuery
  121. * @param boolean $unique_id see sqimap_session_id()
  122. * @since 1.5.0
  123. */
  124. function sqimap_prepare_pipelined_query($new_query,&$tag,&$aQuery,$unique_id) {
  125. $sid = sqimap_session_id($unique_id);
  126. $tag_uid_a = explode(' ',trim($sid));
  127. $tag = $tag_uid_a[0];
  128. $query = $sid . ' '.$new_query."\r\n";
  129. $aQuery[$tag] = $query;
  130. }
  131. /**
  132. * @param stream $imap_stream imap stream
  133. * @param array $aQueryList
  134. * @param boolean $handle_errors
  135. * @param array $aServerResponse
  136. * @param array $aServerMessage
  137. * @param boolean $unique_id see sqimap_session_id()
  138. * @param boolean $filter see sqimap_fread()
  139. * @param mixed $outputstream see sqimap_fread()
  140. * @param boolean $no_return see sqimap_fread()
  141. * @since 1.5.0
  142. */
  143. function sqimap_run_pipelined_command ($imap_stream, $aQueryList, $handle_errors,
  144. &$aServerResponse, &$aServerMessage, $unique_id = false,
  145. $filter=false,$outputstream=false,$no_return=false) {
  146. $aResponse = false;
  147. /*
  148. Do not fire all calls at once to the IMAP server but split the calls up
  149. in portions of $iChunkSize. If we do not do that I think we misbehave as
  150. IMAP client or should handle BYE calls if the IMAP server drops the
  151. connection because the number of queries is to large. This isn't tested
  152. but a wild guess how it could work in the field.
  153. After testing it on Exchange 2000 we discovered that a chunksize of 32
  154. was quicker then when we raised it to 128.
  155. */
  156. $iQueryCount = count($aQueryList);
  157. $iChunkSize = 32;
  158. // array_chunk would also do the job but it's supported from php > 4.2
  159. $aQueryChunks = array();
  160. $iLoops = floor($iQueryCount / $iChunkSize);
  161. if ($iLoops * $iChunkSize != $iQueryCount) ++$iLoops;
  162. if (!function_exists('array_chunk')) { // arraychunk replacement
  163. reset($aQueryList);
  164. for($i=0;$i<$iLoops;++$i) {
  165. for($j=0;$j<$iChunkSize;++$j) {
  166. $key = key($aQueryList);
  167. $aTmp[$key] = $aQueryList[$key];
  168. if (next($aQueryList) === false) break;
  169. }
  170. $aQueryChunks[] = $aTmp;
  171. }
  172. } else {
  173. $aQueryChunks = array_chunk($aQueryList,$iChunkSize,true);
  174. }
  175. for ($i=0;$i<$iLoops;++$i) {
  176. $aQuery = $aQueryChunks[$i];
  177. foreach($aQuery as $tag => $query) {
  178. fputs($imap_stream,$query);
  179. $aResults[$tag] = false;
  180. }
  181. foreach($aQuery as $tag => $query) {
  182. if ($aResults[$tag] == false) {
  183. $aReturnedResponse = sqimap_retrieve_imap_response ($imap_stream, $tag,
  184. $handle_errors, $response, $message, $query,
  185. $filter,$outputstream,$no_return);
  186. foreach ($aReturnedResponse as $returned_tag => $aResponse) {
  187. if (!empty($aResponse)) {
  188. $aResults[$returned_tag] = $aResponse[0];
  189. } else {
  190. $aResults[$returned_tag] = $aResponse;
  191. }
  192. $aServerResponse[$returned_tag] = $response[$returned_tag];
  193. $aServerMessage[$returned_tag] = $message[$returned_tag];
  194. }
  195. }
  196. }
  197. }
  198. return $aResults;
  199. }
  200. /**
  201. * Custom fgets function: gets a line from the IMAP server,
  202. * no matter how big it may be.
  203. * @param stream $imap_stream the stream to read from
  204. * @return string a line
  205. * @since 1.2.8
  206. */
  207. function sqimap_fgets($imap_stream) {
  208. $read = '';
  209. $buffer = 4096;
  210. $results = '';
  211. $offset = 0;
  212. while (strpos($results, "\r\n", $offset) === false) {
  213. if (!($read = fgets($imap_stream, $buffer))) {
  214. /* this happens in case of an error */
  215. /* reset $results because it's useless */
  216. $results = false;
  217. break;
  218. }
  219. if ( $results != '' ) {
  220. $offset = strlen($results) - 1;
  221. }
  222. $results .= $read;
  223. }
  224. return $results;
  225. }
  226. /**
  227. * @param stream $imap_stream
  228. * @param integer $iSize
  229. * @param boolean $filter
  230. * @param mixed $outputstream stream or 'php://stdout' string
  231. * @param boolean $no_return controls data returned by function
  232. * @return string
  233. * @since 1.4.1
  234. */
  235. function sqimap_fread($imap_stream,$iSize,$filter=false,
  236. $outputstream=false, $no_return=false) {
  237. if (!$filter || !$outputstream) {
  238. $iBufferSize = $iSize;
  239. } else {
  240. // see php bug 24033. They changed fread behaviour %$^&$%
  241. $iBufferSize = 7800; // multiple of 78 in case of base64 decoding.
  242. }
  243. if ($iSize < $iBufferSize) {
  244. $iBufferSize = $iSize;
  245. }
  246. $iRetrieved = 0;
  247. $results = '';
  248. $sRead = $sReadRem = '';
  249. // NB: fread can also stop at end of a packet on sockets.
  250. while ($iRetrieved < $iSize) {
  251. $sRead = fread($imap_stream,$iBufferSize);
  252. $iLength = strlen($sRead);
  253. $iRetrieved += $iLength ;
  254. $iRemaining = $iSize - $iRetrieved;
  255. if ($iRemaining < $iBufferSize) {
  256. $iBufferSize = $iRemaining;
  257. }
  258. if ($sRead == '') {
  259. $results = false;
  260. break;
  261. }
  262. if ($sReadRem != '') {
  263. $sRead = $sReadRem . $sRead;
  264. $sReadRem = '';
  265. }
  266. if ($filter && $sRead != '') {
  267. // in case the filter is base64 decoding we return a remainder
  268. $sReadRem = $filter($sRead);
  269. }
  270. if ($outputstream && $sRead != '') {
  271. if (is_resource($outputstream)) {
  272. fwrite($outputstream,$sRead);
  273. } else if ($outputstream == 'php://stdout') {
  274. echo $sRead;
  275. }
  276. }
  277. if ($no_return) {
  278. $sRead = '';
  279. } else {
  280. $results .= $sRead;
  281. }
  282. }
  283. return $results;
  284. }
  285. /**
  286. * Obsolete function, inform plugins that use it
  287. * @param stream $imap_stream
  288. * @param string $tag
  289. * @param boolean $handle_errors
  290. * @param array $response
  291. * @param array $message
  292. * @param string $query
  293. * @since 1.1.3
  294. * @deprecated (since 1.5.0) use sqimap_run_command or sqimap_run_command_list instead
  295. */
  296. function sqimap_read_data_list($imap_stream, $tag, $handle_errors,
  297. &$response, &$message, $query = '') {
  298. global $color, $squirrelmail_language;
  299. set_up_language($squirrelmail_language);
  300. require_once(SM_PATH . 'functions/display_messages.php');
  301. $string = "<b><font color=\"$color[2]\">\n" .
  302. _("ERROR: Bad function call.") .
  303. "</b><br />\n" .
  304. _("Reason:") . ' '.
  305. 'There is a plugin installed which make use of the <br />' .
  306. 'SquirrelMail internal function sqimap_read_data_list.<br />'.
  307. 'Please adapt the installed plugin and let it use<br />'.
  308. 'sqimap_run_command or sqimap_run_command_list instead<br /><br />'.
  309. 'The following query was issued:<br />'.
  310. htmlspecialchars($query) . '<br />' . "</font><br />\n";
  311. error_box($string,$color);
  312. echo '</body></html>';
  313. exit;
  314. }
  315. /**
  316. * Function to display an error related to an IMAP query.
  317. * @param string title the caption of the error box
  318. * @param string query the query that went wrong
  319. * @param string message_title optional message title
  320. * @param string message optional error message
  321. * @param string $link an optional link to try again
  322. * @return void
  323. * @since 1.5.0
  324. */
  325. function sqimap_error_box($title, $query = '', $message_title = '', $message = '', $link = '')
  326. {
  327. global $color, $squirrelmail_language;
  328. set_up_language($squirrelmail_language);
  329. require_once(SM_PATH . 'functions/display_messages.php');
  330. $string = "<font color=\"$color[2]\"><b>\n" . $title . "</b><br />\n";
  331. $cmd = explode(' ',$query);
  332. $cmd= strtolower($cmd[0]);
  333. if ($query != '' && $cmd != 'login')
  334. $string .= _("Query:") . ' ' . htmlspecialchars($query) . '<br />';
  335. if ($message_title != '')
  336. $string .= $message_title;
  337. if ($message != '')
  338. $string .= htmlspecialchars($message);
  339. $string .= "</font><br />\n";
  340. if ($link != '')
  341. $string .= $link;
  342. error_box($string,$color);
  343. }
  344. /**
  345. * Reads the output from the IMAP stream. If handle_errors is set to true,
  346. * this will also handle all errors that are received. If it is not set,
  347. * the errors will be sent back through $response and $message.
  348. * @param stream $imap_stream imap stream
  349. * @param string $tag
  350. * @param boolean $handle_errors handle errors internally or send them in $response and $message.
  351. * @param array $response
  352. * @param array $message
  353. * @param string $query command that can be printed if something fails
  354. * @param boolean $filter see sqimap_fread()
  355. * @param mixed $outputstream see sqimap_fread()
  356. * @param boolean $no_return see sqimap_fread()
  357. * @since 1.5.0
  358. */
  359. function sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
  360. &$response, &$message, $query = '',
  361. $filter = false, $outputstream = false, $no_return = false) {
  362. global $color, $squirrelmail_language;
  363. $read = '';
  364. if (!is_array($message)) $message = array();
  365. if (!is_array($response)) $response = array();
  366. $aResponse = '';
  367. $resultlist = array();
  368. $data = array();
  369. $read = sqimap_fgets($imap_stream);
  370. $i = 0;
  371. while ($read) {
  372. $char = $read{0};
  373. switch ($char)
  374. {
  375. case '+':
  376. default:
  377. $read = sqimap_fgets($imap_stream);
  378. break;
  379. case $tag{0}:
  380. {
  381. /* get the command */
  382. $arg = '';
  383. $i = strlen($tag)+1;
  384. $s = substr($read,$i);
  385. if (($j = strpos($s,' ')) || ($j = strpos($s,"\n"))) {
  386. $arg = substr($s,0,$j);
  387. }
  388. $found_tag = substr($read,0,$i-1);
  389. if ($found_tag) {
  390. switch ($arg)
  391. {
  392. case 'OK':
  393. case 'BAD':
  394. case 'NO':
  395. case 'BYE':
  396. case 'PREAUTH':
  397. $response[$found_tag] = $arg;
  398. $message[$found_tag] = trim(substr($read,$i+strlen($arg)));
  399. if (!empty($data)) {
  400. $resultlist[] = $data;
  401. }
  402. $aResponse[$found_tag] = $resultlist;
  403. $data = $resultlist = array();
  404. if ($found_tag == $tag) {
  405. break 3; /* switch switch while */
  406. }
  407. break;
  408. default:
  409. /* this shouldn't happen */
  410. $response[$found_tag] = $arg;
  411. $message[$found_tag] = trim(substr($read,$i+strlen($arg)));
  412. if (!empty($data)) {
  413. $resultlist[] = $data;
  414. }
  415. $aResponse[$found_tag] = $resultlist;
  416. $data = $resultlist = array();
  417. if ($found_tag == $tag) {
  418. break 3; /* switch switch while */
  419. }
  420. }
  421. }
  422. $read = sqimap_fgets($imap_stream);
  423. if ($read === false) { /* error */
  424. break 2; /* switch while */
  425. }
  426. break;
  427. } // end case $tag{0}
  428. case '*':
  429. {
  430. if (preg_match('/^\*\s\d+\sFETCH/',$read)) {
  431. /* check for literal */
  432. $s = substr($read,-3);
  433. $fetch_data = array();
  434. do { /* outer loop, continue until next untagged fetch
  435. or tagged reponse */
  436. do { /* innerloop for fetching literals. with this loop
  437. we prohibid that literal responses appear in the
  438. outer loop so we can trust the untagged and
  439. tagged info provided by $read */
  440. if ($s === "}\r\n") {
  441. $j = strrpos($read,'{');
  442. $iLit = substr($read,$j+1,-3);
  443. $fetch_data[] = $read;
  444. $sLiteral = sqimap_fread($imap_stream,$iLit,$filter,$outputstream,$no_return);
  445. if ($sLiteral === false) { /* error */
  446. break 4; /* while while switch while */
  447. }
  448. /* backwards compattibility */
  449. $aLiteral = explode("\n", $sLiteral);
  450. /* release not neaded data */
  451. unset($sLiteral);
  452. foreach ($aLiteral as $line) {
  453. $fetch_data[] = $line ."\n";
  454. }
  455. /* release not neaded data */
  456. unset($aLiteral);
  457. /* next fgets belongs to this fetch because
  458. we just got the exact literalsize and there
  459. must follow data to complete the response */
  460. $read = sqimap_fgets($imap_stream);
  461. if ($read === false) { /* error */
  462. break 4; /* while while switch while */
  463. }
  464. $fetch_data[] = $read;
  465. } else {
  466. $fetch_data[] = $read;
  467. }
  468. /* retrieve next line and check in the while
  469. statements if it belongs to this fetch response */
  470. $read = sqimap_fgets($imap_stream);
  471. if ($read === false) { /* error */
  472. break 4; /* while while switch while */
  473. }
  474. /* check for next untagged reponse and break */
  475. if ($read{0} == '*') break 2;
  476. $s = substr($read,-3);
  477. } while ($s === "}\r\n");
  478. $s = substr($read,-3);
  479. } while ($read{0} !== '*' &&
  480. substr($read,0,strlen($tag)) !== $tag);
  481. $resultlist[] = $fetch_data;
  482. /* release not neaded data */
  483. unset ($fetch_data);
  484. } else {
  485. $s = substr($read,-3);
  486. do {
  487. if ($s === "}\r\n") {
  488. $j = strrpos($read,'{');
  489. $iLit = substr($read,$j+1,-3);
  490. $data[] = $read;
  491. $sLiteral = fread($imap_stream,$iLit);
  492. if ($sLiteral === false) { /* error */
  493. $read = false;
  494. break 3; /* while switch while */
  495. }
  496. $data[] = $sLiteral;
  497. $data[] = sqimap_fgets($imap_stream);
  498. } else {
  499. $data[] = $read;
  500. }
  501. $read = sqimap_fgets($imap_stream);
  502. if ($read === false) {
  503. break 3; /* while switch while */
  504. } else if ($read{0} == '*') {
  505. break;
  506. }
  507. $s = substr($read,-3);
  508. } while ($s === "}\r\n");
  509. break 1;
  510. }
  511. break;
  512. } // end case '*'
  513. } // end switch
  514. } // end while
  515. /* error processing in case $read is false */
  516. if ($read === false) {
  517. // try to retrieve an untagged bye respons from the results
  518. $sResponse = array_pop($data);
  519. if ($sResponse !== NULL && strpos($sResponse,'* BYE') !== false) {
  520. if (!$handle_errors) {
  521. $query = '';
  522. }
  523. sqimap_error_box(_("ERROR: IMAP server closed the connection."), $query, _("Server responded:"),$sResponse);
  524. echo '</body></html>';
  525. exit;
  526. } else if ($handle_errors) {
  527. unset($data);
  528. sqimap_error_box(_("ERROR: Connection dropped by IMAP server."), $query);
  529. exit;
  530. }
  531. }
  532. /* Set $resultlist array */
  533. if (!empty($data)) {
  534. //$resultlist[] = $data;
  535. }
  536. elseif (empty($resultlist)) {
  537. $resultlist[] = array();
  538. }
  539. /* Return result or handle errors */
  540. if ($handle_errors == false) {
  541. return $aResponse;
  542. }
  543. switch ($response[$tag]) {
  544. case 'OK':
  545. return $aResponse;
  546. break;
  547. case 'NO':
  548. /* ignore this error from M$ exchange, it is not fatal (aka bug) */
  549. if (strstr($message[$tag], 'command resulted in') === false) {
  550. sqimap_error_box(_("ERROR: Could not complete request."), $query, _("Reason Given:") . ' ', $message[$tag]);
  551. echo '</body></html>';
  552. exit;
  553. }
  554. break;
  555. case 'BAD':
  556. sqimap_error_box(_("ERROR: Bad or malformed request."), $query, _("Server responded:") . ' ', $message[$tag]);
  557. echo '</body></html>';
  558. exit;
  559. case 'BYE':
  560. sqimap_error_box(_("ERROR: IMAP server closed the connection."), $query, _("Server responded:") . ' ', $message[$tag]);
  561. echo '</body></html>';
  562. exit;
  563. default:
  564. sqimap_error_box(_("ERROR: Unknown IMAP response."), $query, _("Server responded:") . ' ', $message[$tag]);
  565. /* the error is displayed but because we don't know the reponse we
  566. return the result anyway */
  567. return $aResponse;
  568. break;
  569. }
  570. }
  571. /**
  572. * @param stream $imap_stream imap string
  573. * @param string $tag_uid
  574. * @param boolean $handle_errors
  575. * @param array $response
  576. * @param array $message
  577. * @param string $query (since 1.2.5)
  578. * @param boolean $filter (since 1.4.1) see sqimap_fread()
  579. * @param mixed $outputstream (since 1.4.1) see sqimap_fread()
  580. * @param boolean $no_return (since 1.4.1) see sqimap_fread()
  581. */
  582. function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors,
  583. &$response, &$message, $query = '',
  584. $filter=false,$outputstream=false,$no_return=false) {
  585. $tag_uid_a = explode(' ',trim($tag_uid));
  586. $tag = $tag_uid_a[0];
  587. $res = sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
  588. $response, $message, $query,$filter,$outputstream,$no_return);
  589. return $res;
  590. }
  591. /**
  592. * Connects to the IMAP server and returns a resource identifier for use with
  593. * the other SquirrelMail IMAP functions. Does NOT login!
  594. * @param string server hostname of IMAP server
  595. * @param int port port number to connect to
  596. * @param integer $tls whether to use plain text(0), TLS(1) or STARTTLS(2) when connecting.
  597. * Argument was boolean before 1.5.1.
  598. * @return imap-stream resource identifier
  599. * @since 1.5.0 (usable only in 1.5.1 or later)
  600. */
  601. function sqimap_create_stream($server,$port,$tls=0) {
  602. global $squirrelmail_language;
  603. if (strstr($server,':') && ! preg_match("/^\[.*\]$/",$server)) {
  604. // numerical IPv6 address must be enclosed in square brackets
  605. $server = '['.$server.']';
  606. }
  607. if ($tls == 1) {
  608. if ((check_php_version(4,3)) and (extension_loaded('openssl'))) {
  609. /* Use TLS by prefixing "tls://" to the hostname */
  610. $server = 'tls://' . $server;
  611. } else {
  612. require_once(SM_PATH . 'functions/display_messages.php');
  613. logout_error( sprintf(_("Error connecting to IMAP server: %s."), $server).
  614. '<br />'.
  615. _("TLS is enabled, but this version of PHP does not support TLS sockets, or is missing the openssl extension.").
  616. '<br /><br />'.
  617. _("Please contact your system administrator and report this error."),
  618. sprintf(_("Error connecting to IMAP server: %s."), $server));
  619. }
  620. }
  621. $imap_stream = @fsockopen($server, $port, $error_number, $error_string, 15);
  622. /* Do some error correction */
  623. if (!$imap_stream) {
  624. set_up_language($squirrelmail_language, true);
  625. require_once(SM_PATH . 'functions/display_messages.php');
  626. logout_error( sprintf(_("Error connecting to IMAP server: %s."), $server).
  627. "<br />\r\n$error_number : $error_string<br />\r\n",
  628. sprintf(_("Error connecting to IMAP server: %s."), $server) );
  629. exit;
  630. }
  631. $server_info = fgets ($imap_stream, 1024);
  632. /**
  633. * Implementing IMAP STARTTLS (rfc2595) in php 5.1.0+
  634. * http://www.php.net/stream-socket-enable-crypto
  635. */
  636. if ($tls == 2) {
  637. if (function_exists('stream_socket_enable_crypto')) {
  638. // check starttls capability, don't use cached capability version
  639. if (! sqimap_capability($imap_stream, 'STARTTLS', false)) {
  640. // imap server does not declare starttls support
  641. sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
  642. '','',
  643. _("IMAP STARTTLS is enabled in SquirrelMail configuration, but used IMAP server does not support STARTTLS."));
  644. exit;
  645. }
  646. // issue starttls command and check response
  647. sqimap_run_command($imap_stream, 'STARTTLS', false, $starttls_response, $starttls_message);
  648. // check response
  649. if ($starttls_response!='OK') {
  650. // starttls command failed
  651. sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
  652. 'STARTTLS',
  653. _("Server replied:") . ' ',
  654. $starttls_message);
  655. exit();
  656. }
  657. // start crypto on connection. suppress function errors.
  658. if (@stream_socket_enable_crypto($imap_stream,true,STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
  659. // starttls was successful
  660. /**
  661. * RFC 2595 requires to discard CAPABILITY information after successful
  662. * STARTTLS command. We don't follow RFC, because SquirrelMail stores CAPABILITY
  663. * information only after successful login (src/redirect.php) and cached information
  664. * is used only in other php script connections after successful STARTTLS. If script
  665. * issues sqimap_capability() call before sqimap_login() and wants to get initial
  666. * capability response, script should set third sqimap_capability() argument to false.
  667. */
  668. //sqsession_unregister('sqimap_capabilities');
  669. } else {
  670. /**
  671. * stream_socket_enable_crypto() call failed. Possible issues:
  672. * - broken ssl certificate (uw drops connection, error is in syslog mail facility)
  673. * - some ssl error (can reproduce with STREAM_CRYPTO_METHOD_SSLv3_CLIENT, PHP E_WARNING
  674. * suppressed in stream_socket_enable_crypto() call)
  675. */
  676. sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
  677. '','',
  678. _("Unable to start TLS."));
  679. /**
  680. * Bug: stream_socket_enable_crypto() does not register SSL errors in
  681. * openssl_error_string() or stream notification wrapper and displays
  682. * them in E_WARNING level message. It is impossible to retrieve error
  683. * message without own error handler.
  684. */
  685. exit;
  686. }
  687. } else {
  688. // php install does not support stream_socket_enable_crypto() function
  689. sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
  690. '','',
  691. _("IMAP STARTTLS is enabled in SquirrelMail configuration, but used PHP version does not support functions that allow to enable encryption on open socket."));
  692. exit;
  693. }
  694. }
  695. return $imap_stream;
  696. }
  697. /**
  698. * Logs the user into the IMAP server. If $hide is set, no error messages
  699. * will be displayed. This function returns the IMAP connection handle.
  700. * @param string $username user name
  701. * @param string $password encrypted password
  702. * @param string $imap_server_address address of imap server
  703. * @param integer $imap_port port of imap server
  704. * @param boolean $hide controls display connection errors
  705. * @return stream
  706. */
  707. function sqimap_login ($username, $password, $imap_server_address, $imap_port, $hide) {
  708. global $color, $squirrelmail_language, $onetimepad, $use_imap_tls,
  709. $imap_auth_mech, $sqimap_capabilities;
  710. if (!isset($onetimepad) || empty($onetimepad)) {
  711. sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION );
  712. }
  713. if (!isset($sqimap_capabilities)) {
  714. sqgetglobalvar('sqimap_capabilities' , $capability , SQ_SESSION );
  715. }
  716. $host = $imap_server_address;
  717. $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
  718. $imap_stream = sqimap_create_stream($imap_server_address,$imap_port,$use_imap_tls);
  719. /* Decrypt the password */
  720. $password = OneTimePadDecrypt($password, $onetimepad);
  721. if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
  722. // We're using some sort of authentication OTHER than plain or login
  723. $tag=sqimap_session_id(false);
  724. if ($imap_auth_mech == 'digest-md5') {
  725. $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
  726. } elseif ($imap_auth_mech == 'cram-md5') {
  727. $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
  728. }
  729. fputs($imap_stream,$query);
  730. $answer=sqimap_fgets($imap_stream);
  731. // Trim the "+ " off the front
  732. $response=explode(" ",$answer,3);
  733. if ($response[0] == '+') {
  734. // Got a challenge back
  735. $challenge=$response[1];
  736. if ($imap_auth_mech == 'digest-md5') {
  737. $reply = digest_md5_response($username,$password,$challenge,'imap',$host);
  738. } elseif ($imap_auth_mech == 'cram-md5') {
  739. $reply = cram_md5_response($username,$password,$challenge);
  740. }
  741. fputs($imap_stream,$reply);
  742. $read=sqimap_fgets($imap_stream);
  743. if ($imap_auth_mech == 'digest-md5') {
  744. // DIGEST-MD5 has an extra step..
  745. if (substr($read,0,1) == '+') { // OK so far..
  746. fputs($imap_stream,"\r\n");
  747. $read=sqimap_fgets($imap_stream);
  748. }
  749. }
  750. $results=explode(" ",$read,3);
  751. $response=$results[1];
  752. $message=$results[2];
  753. } else {
  754. // Fake the response, so the error trap at the bottom will work
  755. $response="BAD";
  756. $message='IMAP server does not appear to support the authentication method selected.';
  757. $message .= ' Please contact your system administrator.';
  758. }
  759. } elseif ($imap_auth_mech == 'login') {
  760. // Original IMAP login code
  761. $query = 'LOGIN "' . quoteimap($username) . '" "' . quoteimap($password) . '"';
  762. $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
  763. } elseif ($imap_auth_mech == 'plain') {
  764. /***
  765. * SASL PLAIN
  766. *
  767. * RFC 2595 Chapter 6
  768. *
  769. * The mechanism consists of a single message from the client to the
  770. * server. The client sends the authorization identity (identity to
  771. * login as), followed by a US-ASCII NUL character, followed by the
  772. * authentication identity (identity whose password will be used),
  773. * followed by a US-ASCII NUL character, followed by the clear-text
  774. * password. The client may leave the authorization identity empty to
  775. * indicate that it is the same as the authentication identity.
  776. *
  777. **/
  778. $tag=sqimap_session_id(false);
  779. $sasl = (isset($capability['SASL-IR']) && $capability['SASL-IR']) ? true : false;
  780. $auth = base64_encode("$username\0$username\0$password");
  781. if ($sasl) {
  782. // IMAP Extension for SASL Initial Client Response
  783. // <draft-siemborski-imap-sasl-initial-response-01b.txt>
  784. $query = $tag . " AUTHENTICATE PLAIN $auth\r\n";
  785. fputs($imap_stream, $query);
  786. $read = sqimap_fgets($imap_stream);
  787. } else {
  788. $query = $tag . " AUTHENTICATE PLAIN\r\n";
  789. fputs($imap_stream, $query);
  790. $read=sqimap_fgets($imap_stream);
  791. if (substr($read,0,1) == '+') { // OK so far..
  792. fputs($imap_stream, "$auth\r\n");
  793. $read = sqimap_fgets($imap_stream);
  794. }
  795. }
  796. $results=explode(" ",$read,3);
  797. $response=$results[1];
  798. $message=$results[2];
  799. } else {
  800. $response="BAD";
  801. $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
  802. }
  803. /* If the connection was not successful, lets see why */
  804. if ($response != 'OK') {
  805. if (!$hide) {
  806. if ($response != 'NO') {
  807. /* "BAD" and anything else gets reported here. */
  808. $message = htmlspecialchars($message);
  809. set_up_language($squirrelmail_language, true);
  810. require_once(SM_PATH . 'functions/display_messages.php');
  811. if ($response == 'BAD') {
  812. $string = sprintf (_("Bad request: %s")."<br />\r\n", $message);
  813. } else {
  814. $string = sprintf (_("Unknown error: %s") . "<br />\n", $message);
  815. }
  816. if (isset($read) && is_array($read)) {
  817. $string .= '<br />' . _("Read data:") . "<br />\n";
  818. foreach ($read as $line) {
  819. $string .= htmlspecialchars($line) . "<br />\n";
  820. }
  821. }
  822. error_box($string,$color);
  823. exit;
  824. } else {
  825. /*
  826. * If the user does not log in with the correct
  827. * username and password it is not possible to get the
  828. * correct locale from the user's preferences.
  829. * Therefore, apply the same hack as on the login
  830. * screen.
  831. *
  832. * $squirrelmail_language is set by a cookie when
  833. * the user selects language and logs out
  834. */
  835. set_up_language($squirrelmail_language, true);
  836. include_once(SM_PATH . 'functions/display_messages.php' );
  837. sqsession_destroy();
  838. /* terminate the session nicely */
  839. sqimap_logout($imap_stream);
  840. logout_error( _("Unknown user or password incorrect.") );
  841. exit;
  842. }
  843. } else {
  844. exit;
  845. }
  846. }
  847. /* Special error case:
  848. * Login referrals. The server returns:
  849. * ? OK [REFERRAL <imap url>]
  850. * Check RFC 2221 for details. Since we do not support login referrals yet
  851. * we log the user out.
  852. */
  853. if ( stristr($message, 'REFERRAL imap') === TRUE ) {
  854. sqimap_logout($imap_stream);
  855. set_up_language($squirrelmail_language, true);
  856. include_once(SM_PATH . 'functions/display_messages.php' );
  857. sqsession_destroy();
  858. logout_error( _("Your mailbox is not located at this server. Try a different server or consult your system administrator") );
  859. exit;
  860. }
  861. return $imap_stream;
  862. }
  863. /**
  864. * Simply logs out the IMAP session
  865. * @param stream $imap_stream the IMAP connection to log out.
  866. * @return void
  867. */
  868. function sqimap_logout ($imap_stream) {
  869. /* Logout is not valid until the server returns 'BYE'
  870. * If we don't have an imap_ stream we're already logged out */
  871. if(isset($imap_stream) && $imap_stream)
  872. sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
  873. }
  874. /**
  875. * Retrieve the CAPABILITY string from the IMAP server.
  876. * If capability is set, returns only that specific capability,
  877. * else returns array of all capabilities.
  878. * @param stream $imap_stream
  879. * @param string $capability (since 1.3.0)
  880. * @param boolean $bUseCache (since 1.5.1) Controls use of capability data stored in session
  881. * @return mixed (string if $capability is set and found,
  882. * false, if $capability is set and not found,
  883. * array if $capability not set)
  884. */
  885. function sqimap_capability($imap_stream, $capability='', $bUseCache=true) {
  886. // sqgetGlobalVar('sqimap_capabilities', $sqimap_capabilities, SQ_SESSION);
  887. if (!$bUseCache || ! sqgetGlobalVar('sqimap_capabilities', $sqimap_capabilities, SQ_SESSION)) {
  888. $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
  889. $c = explode(' ', $read[0]);
  890. for ($i=2; $i < count($c); $i++) {
  891. $cap_list = explode('=', $c[$i]);
  892. if (isset($cap_list[1])) {
  893. $sqimap_capabilities[trim($cap_list[0])][] = $cap_list[1];
  894. } else {
  895. $sqimap_capabilities[trim($cap_list[0])] = TRUE;
  896. }
  897. }
  898. }
  899. if ($capability) {
  900. if (isset($sqimap_capabilities[$capability])) {
  901. return $sqimap_capabilities[$capability];
  902. } else {
  903. return false;
  904. }
  905. }
  906. return $sqimap_capabilities;
  907. }
  908. /**
  909. * Returns the delimiter between mailboxes: INBOX/Test, or INBOX.Test
  910. * @param stream $imap_stream
  911. * @return string
  912. */
  913. function sqimap_get_delimiter ($imap_stream = false) {
  914. global $sqimap_delimiter, $optional_delimiter;
  915. /* Use configured delimiter if set */
  916. if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
  917. return $optional_delimiter;
  918. }
  919. /* Delimiter is stored in the session from redirect. Try fetching from there first */
  920. if (empty($sqimap_delimiter)) {
  921. sqgetGlobalVar('delimiter',$sqimap_delimiter,SQ_SESSION);
  922. }
  923. /* Do some caching here */
  924. if (!$sqimap_delimiter) {
  925. if (sqimap_capability($imap_stream, 'NAMESPACE')) {
  926. /*
  927. * According to something that I can't find, this is supposed to work on all systems
  928. * OS: This won't work in Courier IMAP.
  929. * OS: According to rfc2342 response from NAMESPACE command is:
  930. * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
  931. * OS: We want to lookup all personal NAMESPACES...
  932. */
  933. $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
  934. if (eregi('\\* NAMESPACE +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL) +(\\( *\\(.+\\) *\\)|NIL)', $read[0], $data)) {
  935. if (eregi('^\\( *\\((.*)\\) *\\)', $data[1], $data2)) {
  936. $pn = $data2[1];
  937. }
  938. $pna = explode(')(', $pn);
  939. while (list($k, $v) = each($pna)) {
  940. $lst = explode('"', $v);
  941. if (isset($lst[3])) {
  942. $pn[$lst[1]] = $lst[3];
  943. } else {
  944. $pn[$lst[1]] = '';
  945. }
  946. }
  947. }
  948. $sqimap_delimiter = $pn[0];
  949. } else {
  950. fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
  951. $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
  952. $read = $read['.'][0]; //sqimap_read_data() now returns a tag array of response array
  953. $quote_position = strpos ($read[0], '"');
  954. $sqimap_delimiter = substr ($read[0], $quote_position+1, 1);
  955. }
  956. }
  957. return $sqimap_delimiter;
  958. }
  959. /**
  960. * This encodes a mailbox name for use in IMAP commands.
  961. * @param string $what the mailbox to encode
  962. * @return string the encoded mailbox string
  963. * @since 1.5.0
  964. */
  965. function sqimap_encode_mailbox_name($what)
  966. {
  967. if (ereg("[\"\\\r\n]", $what))
  968. return '{' . strlen($what) . "}\r\n" . $what; /* 4.3 literal form */
  969. return '"' . $what . '"'; /* 4.3 quoted string form */
  970. }
  971. /**
  972. * Gets the number of messages in the current mailbox.
  973. *
  974. * OBSOLETE use sqimap_status_messages instead.
  975. * @param stream $imap_stream imap stream
  976. * @param string $mailbox
  977. * @deprecated
  978. */
  979. function sqimap_get_num_messages ($imap_stream, $mailbox) {
  980. $aStatus = sqimap_status_messages($imap_stream,$mailbox,array('MESSAGES'));
  981. return $aStatus['MESSAGES'];
  982. }
  983. /**
  984. * OBSOLETE FUNCTION should be removed after mailbox_display,
  985. * printMessage function is adapted
  986. * $addr_ar = array(), $group = '' and $host='' arguments are used in 1.4.0
  987. * @param string $address
  988. * @param integer $max
  989. * @since 1.4.0
  990. * @deprecated See Rfc822Address.php
  991. */
  992. function parseAddress($address, $max=0) {
  993. $aAddress = parseRFC822Address($address,array('limit'=> $max));
  994. /*
  995. * Because the expected format of the array element is changed we adapt it now.
  996. * This also implies that this function is obsolete and should be removed after the
  997. * rest of the source is adapted. See Rfc822Address.php for the new function.
  998. */
  999. array_walk($aAddress, '_adaptAddress');
  1000. return $aAddress;
  1001. }
  1002. /**
  1003. * OBSOLETE FUNCTION should be removed after mailbox_display,
  1004. * printMessage function is adapted
  1005. *
  1006. * callback function used for formating of addresses array in
  1007. * parseAddress() function
  1008. * @param array $aAddr
  1009. * @param integer $k array key
  1010. * @since 1.5.1
  1011. * @deprecated
  1012. */
  1013. function _adaptAddress(&$aAddr,$k) {
  1014. $sPersonal = (isset($aAddr[SQM_ADDR_PERSONAL]) && $aAddr[SQM_ADDR_PERSONAL]) ?
  1015. $aAddr[SQM_ADDR_PERSONAL] : '';
  1016. $sEmail = ($aAddr[SQM_ADDR_HOST]) ?
  1017. $aAddr[SQM_ADDR_MAILBOX] . '@'.$aAddr[SQM_ADDR_HOST] :
  1018. $aAddr[SQM_ADDR_MAILBOX];
  1019. $aAddr = array($sEmail,$sPersonal);
  1020. }
  1021. /**
  1022. * Returns the number of unseen messages in this folder.
  1023. * obsoleted by sqimap_status_messages !
  1024. * Arguments differ in 1.0.x
  1025. * @param stream $imap_stream
  1026. * @param string $mailbox
  1027. * @return integer
  1028. * @deprecated
  1029. */
  1030. function sqimap_unseen_messages ($imap_stream, $mailbox) {
  1031. $aStatus = sqimap_status_messages($imap_stream,$mailbox,array('UNSEEN'));
  1032. return $aStatus['UNSEEN'];
  1033. }
  1034. /**
  1035. * Returns the status items of a mailbox.
  1036. * Default it returns MESSAGES,UNSEEN and RECENT
  1037. * Supported status items are MESSAGES, UNSEEN, RECENT (since 1.4.0),
  1038. * UIDNEXT (since 1.5.1) and UIDVALIDITY (since 1.5.1)
  1039. * @param stream $imap_stream imap stream
  1040. * @param string $mailbox mail folder
  1041. * @param array $aStatusItems status items
  1042. * @return array
  1043. * @since 1.3.2
  1044. */
  1045. function sqimap_status_messages ($imap_stream, $mailbox,
  1046. $aStatusItems = array('MESSAGES','UNSEEN','RECENT')) {
  1047. $aStatusItems = implode(' ',$aStatusItems);
  1048. $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) .
  1049. " ($aStatusItems)", false, $result, $message);
  1050. $i = 0;
  1051. $messages = $unseen = $recent = $uidnext = $uidvalidity = false;
  1052. $regs = array(false,false);
  1053. while (isset($read_ary[$i])) {
  1054. if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
  1055. $unseen = $regs[1];
  1056. }
  1057. if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
  1058. $messages = $regs[1];
  1059. }
  1060. if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
  1061. $recent = $regs[1];
  1062. }
  1063. if (preg_match('/UIDNEXT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
  1064. $uidnext = $regs[1];
  1065. }
  1066. if (preg_match('/UIDVALIDITY\s+([0-9]+)/i', $read_ary[$i], $regs)) {
  1067. $uidvalidity = $regs[1];
  1068. }
  1069. $i++;
  1070. }
  1071. $status=array('MESSAGES' => $messages,
  1072. 'UNSEEN'=>$unseen,
  1073. 'RECENT' => $recent,
  1074. 'UIDNEXT' => $uidnext,
  1075. 'UIDVALIDITY' => $uidvalidity);
  1076. if (!empty($messages)) { $hook_status['MESSAGES']=$messages; }
  1077. if (!empty($unseen)) { $hook_status['UNSEEN']=$unseen; }
  1078. if (!empty($recent)) { $hook_status['RECENT']=$recent; }
  1079. if (!empty($hook_status)) {
  1080. $hook_status['MAILBOX']=$mailbox;
  1081. $hook_status['CALLER']='sqimap_status_messages';
  1082. do_hook_function('folder_status',$hook_status);
  1083. }
  1084. return $status;
  1085. }
  1086. /**
  1087. * Saves a message to a given folder -- used for saving sent messages
  1088. * @param stream $imap_stream
  1089. * @param string $sent_folder
  1090. * @param $length
  1091. * @return string $sid
  1092. */
  1093. function sqimap_append ($imap_stream, $sMailbox, $length) {
  1094. $sid = sqimap_session_id();
  1095. $query = $sid . ' APPEND ' . sqimap_encode_mailbox_name($sMailbox) . " (\\Seen) {".$length."}";
  1096. fputs ($imap_stream, "$query\r\n");
  1097. $tmp = fgets ($imap_stream, 1024);
  1098. sqimap_append_checkresponse($tmp, $sMailbox,$sid, $query);
  1099. return $sid;
  1100. }
  1101. /**
  1102. * @param stream imap_stream
  1103. * @param string $folder (since 1.3.2)
  1104. */
  1105. function sqimap_append_done ($imap_stream, $sMailbox='') {
  1106. fputs ($imap_stream, "\r\n");
  1107. $tmp = fgets ($imap_stream, 1024);
  1108. while (!sqimap_append_checkresponse($tmp, $sMailbox)) {
  1109. $tmp = fgets ($imap_stream, 1024);
  1110. }
  1111. }
  1112. /**
  1113. * Displays error messages, if there are errors in responses to
  1114. * commands issues by sqimap_append() and sqimap_append_done() functions.
  1115. * @param string $response
  1116. * @param string $sMailbox
  1117. * @return bool $bDone
  1118. * @since 1.5.1 and 1.4.5
  1119. */
  1120. function sqimap_append_checkresponse($response, $sMailbox, $sid='', $query='') {
  1121. // static vars to keep them available when sqimap_append_done calls this function.
  1122. static $imapquery, $imapsid;
  1123. $bDone = false;
  1124. if ($query) {
  1125. $imapquery = $query;
  1126. }
  1127. if ($sid) {
  1128. $imapsid = $sid;
  1129. }
  1130. if ($response{0} == '+') {
  1131. // continuation request triggerd by sqimap_append()
  1132. $bDone = true;
  1133. } else {
  1134. $i = strpos($response, ' ');
  1135. $sRsp = substr($response,0,$i);
  1136. $sMsg = substr($response,$i+1);
  1137. $aExtra = array('MAILBOX' => $sMailbox);
  1138. switch ($sRsp) {
  1139. case '*': //untagged response
  1140. $i = strpos($sMsg, ' ');
  1141. $sRsp = strtoupper(substr($sMsg,0,$i));
  1142. $sMsg = substr($sMsg,$i+1);
  1143. if ($sRsp == 'NO' || $sRsp == 'BAD') {
  1144. // for the moment disabled. Enable after 1.5.1 release.
  1145. // Notices could give valueable information about the mailbox
  1146. // sqm_trigger_imap_error('SQM_IMAP_APPEND_NOTICE',$imapquery,$sRsp,$sMsg);
  1147. }
  1148. $bDone = false;
  1149. case $imapsid:
  1150. // A001 OK message
  1151. // $imapsid<space>$sRsp<space>$sMsg
  1152. $bDone = true;
  1153. $i = strpos($sMsg, ' ');
  1154. $sRsp = strtoupper(substr($sMsg,0,$i));
  1155. $sMsg = substr($sMsg,$i+1);
  1156. switch ($sRsp) {
  1157. case 'NO':
  1158. if (preg_match("/(.*)(quota)(.*)$/i", $sMsg, $aMatch)) {
  1159. sqm_trigger_imap_error('SQM_IMAP_APPEND_QUOTA_ERROR',$imapquery,$sRsp,$sMsg,$aExtra);
  1160. } else {
  1161. sqm_trigger_imap_error('SQM_IMAP_APPEND_ERROR',$imapquery,$sRsp,$sMsg,$aExtra);
  1162. }
  1163. break;
  1164. case 'BAD':
  1165. sqm_trigger_imap_error('SQM_IMAP_ERROR',$imapquery,$sRsp,$sMsg,$aExtra);
  1166. break;
  1167. case 'BYE':
  1168. sqm_trigger_imap_error('SQM_IMAP_BYE',$imapquery,$sRsp,$sMsg,$aExtra);
  1169. break;
  1170. case 'OK':
  1171. break;
  1172. default:
  1173. break;
  1174. }
  1175. break;
  1176. default:
  1177. // should be false because of the unexpected response but i'm not sure if
  1178. // that will cause an endless loop in sqimap_append_done
  1179. $bDone = true;
  1180. }
  1181. }
  1182. return $bDone;
  1183. }
  1184. /**
  1185. * Allows mapping of IMAP server address with custom function
  1186. * see map_yp_alias()
  1187. * @param string $imap_server imap server address or mapping
  1188. * @param string $username
  1189. * @return string
  1190. * @since 1.3.0
  1191. */
  1192. function sqimap_get_user_server ($imap_server, $username) {
  1193. if (substr($imap_server, 0, 4) != "map:") {
  1194. return $imap_server;
  1195. }
  1196. $function = substr($imap_server, 4);
  1197. return $function($username);
  1198. }
  1199. /**
  1200. * This is an example that gets IMAP servers from yellowpages (NIS).
  1201. * you can simple put map:map_yp_alias in your $imap_server_address
  1202. * in config.php use your own function instead map_yp_alias to map your
  1203. * LDAP whatever way to find the users IMAP server.
  1204. *
  1205. * Requires access to external ypmatch program
  1206. * FIXME: it can be implemented in php yp extension or pe…

Large files files are truncated, but you can click here to view the full file