PageRenderTime 58ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/branches/smcookies/squirrelmail/functions/imap_general.php

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