imap_general.php 38 KB

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