imap_general.php 38 KB

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