imap_general.php 41 KB

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