imap_general.php 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715
  1. <?php
  2. /**
  3. * imap_general.php
  4. *
  5. * This implements all functions that do general IMAP functions.
  6. *
  7. * @copyright 1999-2025 The SquirrelMail Project Team
  8. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  9. * @version $Id$
  10. * @package squirrelmail
  11. * @subpackage imap
  12. */
  13. /** Includes.. */
  14. require_once(SM_PATH . 'functions/rfc822address.php');
  15. /**
  16. * Generates a new session ID by incrementing the last one used;
  17. * this ensures that each command has a unique ID.
  18. * @param bool $unique_id (since 1.3.0) controls use of unique
  19. * identifiers/message sequence numbers in IMAP commands. See IMAP
  20. * rfc 'UID command' chapter.
  21. * @return string IMAP session id of the form 'A000'.
  22. * @since 1.2.0
  23. */
  24. function sqimap_session_id($unique_id = FALSE) {
  25. static $sqimap_session_id = 1;
  26. if (!$unique_id) {
  27. return( sprintf("A%03d", $sqimap_session_id++) );
  28. } else {
  29. return( sprintf("A%03d", $sqimap_session_id++) . ' UID' );
  30. }
  31. }
  32. /**
  33. * Both send a command and accept the result from the command.
  34. * This is to allow proper session number handling.
  35. * @param stream $imap_stream imap connection resource
  36. * @param string $query imap command
  37. * @param boolean $handle_errors see sqimap_retrieve_imap_response()
  38. * @param array $response
  39. * @param array $message
  40. * @param boolean $unique_id (since 1.3.0) see sqimap_session_id().
  41. * @return mixed returns false on imap error. displays error message
  42. * if imap stream is not available.
  43. * @since 1.2.3
  44. */
  45. function sqimap_run_command_list ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
  46. if ($imap_stream) {
  47. $sid = sqimap_session_id($unique_id);
  48. fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
  49. $tag_uid_a = explode(' ',trim($sid));
  50. $tag = $tag_uid_a[0];
  51. $read = sqimap_retrieve_imap_response ($imap_stream, $tag, $handle_errors, $response, $message, $query );
  52. /* get the response and the message */
  53. $message = $message[$tag];
  54. $response = $response[$tag];
  55. return $read[$tag];
  56. //FIXME: obey $handle_errors below!
  57. } else {
  58. global $squirrelmail_language, $color;
  59. set_up_language($squirrelmail_language);
  60. //FIXME: NO HTML IN CORE!
  61. $string = "<b><font color=\"$color[2]\">\n" .
  62. _("ERROR: No available IMAP stream.") .
  63. //FIXME: NO HTML IN CORE!
  64. "</b></font>\n";
  65. error_box($string);
  66. return false;
  67. }
  68. }
  69. /**
  70. * @param stream $imap_stream imap connection resource
  71. * @param string $query imap command
  72. * @param boolean $handle_errors see sqimap_retrieve_imap_response()
  73. * @param array $response empty string, if return = false
  74. * @param array $message empty string, if return = false
  75. * @param boolean $unique_id (since 1.3.0) see sqimap_session_id()
  76. * @param boolean $filter (since 1.4.1 and 1.5.0) see sqimap_fread()
  77. * @param mixed $outputstream (since 1.4.1 and 1.5.0) see sqimap_fread()
  78. * @param boolean $no_return (since 1.4.1 and 1.5.0) see sqimap_fread()
  79. * @return mixed returns false on imap error. displays error message
  80. * if imap stream is not available.
  81. * @since 1.2.3
  82. */
  83. function sqimap_run_command ($imap_stream, $query, $handle_errors, &$response,
  84. &$message, $unique_id = false,$filter=false,
  85. $outputstream=false,$no_return=false) {
  86. if ($imap_stream) {
  87. $sid = sqimap_session_id($unique_id);
  88. fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
  89. $tag_uid_a = explode(' ',trim($sid));
  90. $tag = $tag_uid_a[0];
  91. $read = sqimap_read_data ($imap_stream, $tag, $handle_errors, $response,
  92. $message, $query,$filter,$outputstream,$no_return);
  93. if (empty($read)) { //IMAP server dropped its connection
  94. $response = '';
  95. $message = '';
  96. return false;
  97. }
  98. /* retrieve the response and the message */
  99. $response = $response[$tag];
  100. $message = $message[$tag];
  101. if (!empty($read[$tag])) {
  102. /* sqimap_read_data should be called for one response
  103. but since it just calls sqimap_retrieve_imap_response
  104. which handles multiple responses we need to check for
  105. that and merge the $read[$tag] array IF they are
  106. separated and IF it was a FETCH response. */
  107. if (isset($read[$tag][1]) && is_array($read[$tag][1]) && isset($read[$tag][1][0])
  108. && preg_match('/^\* \d+ FETCH/', $read[$tag][1][0])) {
  109. $result = array();
  110. foreach($read[$tag] as $index => $value) {
  111. $result = array_merge($result, $read[$tag]["$index"]);
  112. }
  113. return $result;
  114. }
  115. return $read[$tag][0];
  116. } else {
  117. return $read[$tag];
  118. }
  119. //FIXME: obey $handle_errors below!
  120. } else {
  121. global $squirrelmail_language, $color;
  122. set_up_language($squirrelmail_language);
  123. //FIXME: NO HTML IN CORE!
  124. $string = "<b><font color=\"$color[2]\">\n" .
  125. _("ERROR: No available IMAP stream.") .
  126. //FIXME: NO HTML IN CORE!
  127. "</b></font>\n";
  128. error_box($string);
  129. return false;
  130. }
  131. }
  132. /**
  133. * @param mixed $new_query
  134. * @param string $tag
  135. * @param array $aQuery
  136. * @param boolean $unique_id see sqimap_session_id()
  137. * @since 1.5.0
  138. */
  139. function sqimap_prepare_pipelined_query($new_query,&$tag,&$aQuery,$unique_id) {
  140. $sid = sqimap_session_id($unique_id);
  141. $tag_uid_a = explode(' ',trim($sid));
  142. $tag = $tag_uid_a[0];
  143. $query = $sid . ' '.$new_query."\r\n";
  144. $aQuery[$tag] = $query;
  145. }
  146. /**
  147. * @param stream $imap_stream imap stream
  148. * @param array $aQueryList
  149. * @param boolean $handle_errors
  150. * @param array $aServerResponse
  151. * @param array $aServerMessage
  152. * @param boolean $unique_id see sqimap_session_id()
  153. * @param boolean $filter see sqimap_fread()
  154. * @param mixed $outputstream see sqimap_fread()
  155. * @param boolean $no_return see sqimap_fread()
  156. * @since 1.5.0
  157. */
  158. function sqimap_run_pipelined_command ($imap_stream, $aQueryList, $handle_errors,
  159. &$aServerResponse, &$aServerMessage, $unique_id = false,
  160. $filter=false,$outputstream=false,$no_return=false) {
  161. $aResponse = false;
  162. /*
  163. Do not fire all calls at once to the IMAP server but split the calls up
  164. in portions of $iChunkSize. If we do not do that I think we misbehave as
  165. IMAP client or should handle BYE calls if the IMAP server drops the
  166. connection because the number of queries is to large. This isn't tested
  167. but a wild guess how it could work in the field.
  168. After testing it on Exchange 2000 we discovered that a chunksize of 32
  169. was quicker then when we raised it to 128.
  170. */
  171. $iQueryCount = count($aQueryList);
  172. $iChunkSize = 32;
  173. // array_chunk would also do the job but it's supported from php > 4.2
  174. $aQueryChunks = array();
  175. $iLoops = floor($iQueryCount / $iChunkSize);
  176. if ($iLoops * $iChunkSize != $iQueryCount) ++$iLoops;
  177. if (!function_exists('array_chunk')) { // arraychunk replacement
  178. reset($aQueryList);
  179. for($i=0;$i<$iLoops;++$i) {
  180. for($j=0;$j<$iChunkSize;++$j) {
  181. $key = key($aQueryList);
  182. $aTmp[$key] = $aQueryList[$key];
  183. if (next($aQueryList) === false) break;
  184. }
  185. $aQueryChunks[] = $aTmp;
  186. }
  187. } else {
  188. $aQueryChunks = array_chunk($aQueryList,$iChunkSize,true);
  189. }
  190. for ($i=0;$i<$iLoops;++$i) {
  191. $aQuery = $aQueryChunks[$i];
  192. foreach($aQuery as $tag => $query) {
  193. fputs($imap_stream,$query);
  194. $aResults[$tag] = false;
  195. }
  196. foreach($aQuery as $tag => $query) {
  197. if ($aResults[$tag] == false) {
  198. $aReturnedResponse = sqimap_retrieve_imap_response ($imap_stream, $tag,
  199. $handle_errors, $response, $message, $query,
  200. $filter,$outputstream,$no_return);
  201. foreach ($aReturnedResponse as $returned_tag => $aResponse) {
  202. if (!empty($aResponse)) {
  203. $aResults[$returned_tag] = $aResponse[0];
  204. } else {
  205. $aResults[$returned_tag] = $aResponse;
  206. }
  207. $aServerResponse[$returned_tag] = $response[$returned_tag];
  208. $aServerMessage[$returned_tag] = $message[$returned_tag];
  209. }
  210. }
  211. }
  212. }
  213. return $aResults;
  214. }
  215. /**
  216. * Custom fgets function: gets a line from the IMAP server,
  217. * no matter how big it may be.
  218. * @param stream $imap_stream the stream to read from
  219. * @return string a line
  220. * @since 1.2.8
  221. */
  222. function sqimap_fgets($imap_stream) {
  223. $read = '';
  224. $buffer = 4096;
  225. $results = '';
  226. $offset = 0;
  227. while (strpos($results, "\r\n", $offset) === false) {
  228. if (!($read = fgets($imap_stream, $buffer))) {
  229. /* this happens in case of an error */
  230. /* reset $results because it's useless */
  231. $results = false;
  232. break;
  233. }
  234. if ( $results != '' ) {
  235. $offset = strlen($results) - 1;
  236. }
  237. $results .= $read;
  238. }
  239. return $results;
  240. }
  241. /**
  242. * @param stream $imap_stream
  243. * @param integer $iSize
  244. * @param boolean $filter
  245. * @param mixed $outputstream stream or 'php://stdout' string
  246. * @param boolean $no_return controls data returned by function
  247. * @return string
  248. * @since 1.4.1
  249. */
  250. function sqimap_fread($imap_stream,$iSize,$filter=false,
  251. $outputstream=false, $no_return=false) {
  252. if (!$filter || !$outputstream) {
  253. $iBufferSize = $iSize;
  254. } else {
  255. // see php bug 24033. They changed fread behaviour %$^&$%
  256. $iBufferSize = 7800; // multiple of 78 in case of base64 decoding.
  257. }
  258. if ($iSize < $iBufferSize) {
  259. $iBufferSize = $iSize;
  260. }
  261. $iRetrieved = 0;
  262. $results = '';
  263. $sRead = $sReadRem = '';
  264. // NB: fread can also stop at end of a packet on sockets.
  265. while ($iRetrieved < $iSize) {
  266. $sRead = fread($imap_stream,$iBufferSize);
  267. $iLength = strlen($sRead);
  268. $iRetrieved += $iLength ;
  269. $iRemaining = $iSize - $iRetrieved;
  270. if ($iRemaining < $iBufferSize) {
  271. $iBufferSize = $iRemaining;
  272. }
  273. if ($sRead == '') {
  274. $results = false;
  275. break;
  276. }
  277. if ($sReadRem != '') {
  278. $sRead = $sReadRem . $sRead;
  279. $sReadRem = '';
  280. }
  281. if ($filter && $sRead != '') {
  282. // in case the filter is base64 decoding we return a remainder
  283. $sReadRem = $filter($sRead);
  284. }
  285. if ($outputstream && $sRead != '') {
  286. if (is_resource($outputstream)) {
  287. fwrite($outputstream,$sRead);
  288. } else if ($outputstream == 'php://stdout') {
  289. echo $sRead;
  290. }
  291. }
  292. if ($no_return) {
  293. $sRead = '';
  294. } else {
  295. $results .= $sRead;
  296. }
  297. }
  298. return $results;
  299. }
  300. /**
  301. * Obsolete function, inform plugins that use it
  302. * @param stream $imap_stream
  303. * @param string $tag
  304. * @param boolean $handle_errors
  305. * @param array $response
  306. * @param array $message
  307. * @param string $query
  308. * @since 1.1.3
  309. * @deprecated (since 1.5.0) use sqimap_run_command or sqimap_run_command_list instead
  310. */
  311. function sqimap_read_data_list($imap_stream, $tag, $handle_errors,
  312. &$response, &$message, $query = '') {
  313. global $color, $oTemplate, $squirrelmail_language;
  314. set_up_language($squirrelmail_language);
  315. //FIXME: NO HTML IN CORE!
  316. $string = "<b><font color=\"$color[2]\">\n" .
  317. _("ERROR: Bad function call.") .
  318. //FIXME: NO HTML IN CORE!
  319. "</b><br />\n" .
  320. _("Reason:") . ' '.
  321. 'There is a plugin installed which make use of the <br />' .
  322. 'SquirrelMail internal function sqimap_read_data_list.<br />'.
  323. 'Please adapt the installed plugin and let it use<br />'.
  324. 'sqimap_run_command or sqimap_run_command_list instead<br /><br />'.
  325. 'The following query was issued:<br />'.
  326. //FIXME: NO HTML IN CORE!
  327. sm_encode_html_special_chars($query) . '<br />' . "</font><br />\n";
  328. error_box($string);
  329. $oTemplate->display('footer.tpl');
  330. exit;
  331. }
  332. /**
  333. * Function to display an error related to an IMAP query.
  334. * @param string title the caption of the error box
  335. * @param string query the query that went wrong
  336. * @param string message_title optional message title
  337. * @param string message optional error message
  338. * @param string $link an optional link to try again
  339. * @return void
  340. * @since 1.5.0
  341. */
  342. function sqimap_error_box($title, $query = '', $message_title = '', $message = '', $link = '')
  343. {
  344. global $color, $squirrelmail_language;
  345. set_up_language($squirrelmail_language);
  346. //FIXME: NO HTML IN CORE!
  347. $string = "<font color=\"$color[2]\"><b>\n" . $title . "</b><br />\n";
  348. $cmd = explode(' ',$query);
  349. $cmd= strtolower($cmd[0]);
  350. if ($query != '' && $cmd != 'login')
  351. $string .= _("Query:") . ' ' . sm_encode_html_special_chars($query) . '<br />';
  352. if ($message_title != '')
  353. $string .= $message_title;
  354. if ($message != '')
  355. $string .= sm_encode_html_special_chars($message);
  356. //FIXME: NO HTML IN CORE!
  357. $string .= "</font><br />\n";
  358. if ($link != '')
  359. $string .= $link;
  360. error_box($string);
  361. }
  362. /**
  363. * Reads the output from the IMAP stream. If handle_errors is set to true,
  364. * this will also handle all errors that are received. If it is not set,
  365. * the errors will be sent back through $response and $message.
  366. * @param stream $imap_stream imap stream
  367. * @param string $tag
  368. * @param boolean $handle_errors handle errors internally or send them in $response and $message.
  369. * @param array $response
  370. * @param array $message
  371. * @param string $query command that can be printed if something fails
  372. * @param boolean $filter see sqimap_fread()
  373. * @param mixed $outputstream see sqimap_fread()
  374. * @param boolean $no_return see sqimap_fread()
  375. * @since 1.5.0
  376. */
  377. function sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
  378. &$response, &$message, $query = '',
  379. $filter = false, $outputstream = false, $no_return = false) {
  380. global $color, $squirrelmail_language;
  381. $read = '';
  382. if (!is_array($message)) $message = array();
  383. if (!is_array($response)) $response = array();
  384. $aResponse = array();
  385. $resultlist = array();
  386. $data = array();
  387. $sCommand = '';
  388. if (preg_match("/^(\w+)\s*/",$query,$aMatch)) {
  389. $sCommand = strtoupper($aMatch[1]);
  390. } else {
  391. // error reporting (shouldn't happen)
  392. }
  393. $read = sqimap_fgets($imap_stream);
  394. $i = 0;
  395. while ($read) {
  396. $char = $read[0];
  397. switch ($char)
  398. {
  399. case '+':
  400. default:
  401. $read = sqimap_fgets($imap_stream);
  402. break;
  403. case $tag[0]:
  404. {
  405. /* get the command */
  406. $arg = '';
  407. $i = strlen($tag)+1;
  408. $s = substr($read,$i);
  409. if (($j = strpos($s,' ')) || ($j = strpos($s,"\n"))) {
  410. $arg = substr($s,0,$j);
  411. }
  412. $found_tag = substr($read,0,$i-1);
  413. if ($found_tag) {
  414. switch ($arg)
  415. {
  416. case 'OK':
  417. case 'BAD':
  418. case 'NO':
  419. case 'BYE':
  420. case 'PREAUTH':
  421. $response[$found_tag] = $arg;
  422. $message[$found_tag] = trim(substr($read,$i+strlen($arg)));
  423. if (!empty($data)) {
  424. $resultlist[] = $data;
  425. }
  426. $aResponse[$found_tag] = $resultlist;
  427. $data = $resultlist = array();
  428. if ($found_tag == $tag) {
  429. break 3; /* switch switch while */
  430. }
  431. break;
  432. default:
  433. /* this shouldn't happen */
  434. $response[$found_tag] = $arg;
  435. $message[$found_tag] = trim(substr($read,$i+strlen($arg)));
  436. if (!empty($data)) {
  437. $resultlist[] = $data;
  438. }
  439. $aResponse[$found_tag] = $resultlist;
  440. $data = $resultlist = array();
  441. if ($found_tag == $tag) {
  442. break 3; /* switch switch while */
  443. }
  444. }
  445. }
  446. $read = sqimap_fgets($imap_stream);
  447. if ($read === false) { /* error */
  448. break 2; /* switch while */
  449. }
  450. break;
  451. } // end case $tag[0]
  452. case '*':
  453. {
  454. if (($sCommand == "FETCH" || $sCommand == "STORE") && preg_match('/^\*\s\d+\sFETCH/',$read)) {
  455. /* check for literal */
  456. $s = substr($read,-3);
  457. $fetch_data = array();
  458. do { /* outer loop, continue until next untagged fetch
  459. or tagged reponse */
  460. do { /* innerloop for fetching literals. with this loop
  461. we prohibid that literal responses appear in the
  462. outer loop so we can trust the untagged and
  463. tagged info provided by $read */
  464. $read_literal = false;
  465. if ($s === "}\r\n") {
  466. $j = strrpos($read,'{');
  467. $iLit = substr($read,$j+1,-3);
  468. $fetch_data[] = $read;
  469. $sLiteral = sqimap_fread($imap_stream,$iLit,$filter,$outputstream,$no_return);
  470. if ($sLiteral === false) { /* error */
  471. break 4; /* while while switch while */
  472. }
  473. /* backwards compattibility */
  474. $aLiteral = explode("\n", $sLiteral);
  475. /* release not neaded data */
  476. unset($sLiteral);
  477. foreach ($aLiteral as $line) {
  478. $fetch_data[] = $line ."\n";
  479. }
  480. /* release not neaded data */
  481. unset($aLiteral);
  482. /* next fgets belongs to this fetch because
  483. we just got the exact literalsize and there
  484. must follow data to complete the response */
  485. $read = sqimap_fgets($imap_stream);
  486. if ($read === false) { /* error */
  487. break 4; /* while while switch while */
  488. }
  489. $s = substr($read,-3);
  490. $read_literal = true;
  491. continue;
  492. } else {
  493. $fetch_data[] = $read;
  494. }
  495. /* retrieve next line and check in the while
  496. statements if it belongs to this fetch response */
  497. $read = sqimap_fgets($imap_stream);
  498. if ($read === false) { /* error */
  499. break 4; /* while while switch while */
  500. }
  501. /* check for next untagged reponse and break */
  502. if ($read[0] == '*') break 2;
  503. $s = substr($read,-3);
  504. } while ($s === "}\r\n" || $read_literal);
  505. $s = substr($read,-3);
  506. } while ($read[0] !== '*' &&
  507. substr($read,0,strlen($tag)) !== $tag);
  508. $resultlist[] = $fetch_data;
  509. /* release not neaded data */
  510. unset ($fetch_data);
  511. } else {
  512. $s = substr($read,-3);
  513. do {
  514. if ($s === "}\r\n") {
  515. $j = strrpos($read,'{');
  516. $iLit = substr($read,$j+1,-3);
  517. // check for numeric value to avoid that untagged responses like:
  518. // * OK [PARSE] Unexpected characters at end of address: {SET:debug=51}
  519. // will trigger literal fetching ({SET:debug=51} !== int )
  520. if (is_numeric($iLit)) {
  521. $data[] = $read;
  522. $sLiteral = fread($imap_stream,$iLit);
  523. if ($sLiteral === false) { /* error */
  524. $read = false;
  525. break 3; /* while switch while */
  526. }
  527. $data[] = $sLiteral;
  528. $data[] = sqimap_fgets($imap_stream);
  529. } else {
  530. $data[] = $read;
  531. }
  532. } else {
  533. $data[] = $read;
  534. }
  535. $read = sqimap_fgets($imap_stream);
  536. if ($read === false) {
  537. break 3; /* while switch while */
  538. } else if ($read[0] == '*') {
  539. break;
  540. }
  541. $s = substr($read,-3);
  542. } while ($s === "}\r\n");
  543. break 1;
  544. }
  545. break;
  546. } // end case '*'
  547. } // end switch
  548. } // end while
  549. /* error processing in case $read is false */
  550. if ($read === false) {
  551. // try to retrieve an untagged bye respons from the results
  552. $sResponse = array_pop($data);
  553. if ($sResponse !== NULL && strpos($sResponse,'* BYE') !== false) {
  554. if (!$handle_errors) {
  555. $query = '';
  556. }
  557. sqimap_error_box(_("ERROR: IMAP server closed the connection."), $query, _("Server responded:"),$sResponse);
  558. //FIXME: NO HTML IN CORE!
  559. echo '</body></html>';
  560. exit;
  561. } else if ($handle_errors) {
  562. unset($data);
  563. sqimap_error_box(_("ERROR: Connection dropped by IMAP server."), $query);
  564. exit;
  565. }
  566. }
  567. /* Set $resultlist array */
  568. if (!empty($data)) {
  569. //$resultlist[] = $data;
  570. }
  571. elseif (empty($resultlist)) {
  572. $resultlist[] = array();
  573. }
  574. /* Return result or handle errors */
  575. if ($handle_errors == false) {
  576. return $aResponse;
  577. }
  578. switch ($response[$tag]) {
  579. case 'OK':
  580. return $aResponse;
  581. break;
  582. case 'NO':
  583. /* ignore this error from M$ exchange, it is not fatal (aka bug) */
  584. if (strstr($message[$tag], 'command resulted in') === false) {
  585. sqsession_register('NO', 'IMAP_FATAL_ERROR_TYPE');
  586. sqsession_register($query, 'IMAP_FATAL_ERROR_QUERY');
  587. sqsession_register($message[$tag], 'IMAP_FATAL_ERROR_MESSAGE');
  588. sqimap_error_box(_("ERROR: Could not complete request."), $query, _("Reason Given:") . ' ', $message[$tag]);
  589. echo '</body></html>';
  590. exit;
  591. }
  592. break;
  593. case 'BAD':
  594. sqsession_register('BAD', 'IMAP_FATAL_ERROR_TYPE');
  595. sqsession_register($query, 'IMAP_FATAL_ERROR_QUERY');
  596. sqsession_register($message[$tag], 'IMAP_FATAL_ERROR_MESSAGE');
  597. sqimap_error_box(_("ERROR: Bad or malformed request."), $query, _("Server responded:") . ' ', $message[$tag]);
  598. //FIXME: NO HTML IN CORE!
  599. echo '</body></html>';
  600. exit;
  601. case 'BYE':
  602. sqsession_register('BYE', 'IMAP_FATAL_ERROR_TYPE');
  603. sqsession_register($query, 'IMAP_FATAL_ERROR_QUERY');
  604. sqsession_register($message[$tag], 'IMAP_FATAL_ERROR_MESSAGE');
  605. sqimap_error_box(_("ERROR: IMAP server closed the connection."), $query, _("Server responded:") . ' ', $message[$tag]);
  606. //FIXME: NO HTML IN CORE!
  607. echo '</body></html>';
  608. exit;
  609. default:
  610. sqsession_register('UNKNOWN', 'IMAP_FATAL_ERROR_TYPE');
  611. sqsession_register($query, 'IMAP_FATAL_ERROR_QUERY');
  612. sqsession_register($message[$tag], 'IMAP_FATAL_ERROR_MESSAGE');
  613. sqimap_error_box(_("ERROR: Unknown IMAP response."), $query, _("Server responded:") . ' ', $message[$tag]);
  614. /* the error is displayed but because we don't know the reponse we
  615. return the result anyway */
  616. return $aResponse;
  617. break;
  618. }
  619. }
  620. /**
  621. * @param stream $imap_stream imap string
  622. * @param string $tag_uid
  623. * @param boolean $handle_errors
  624. * @param array $response
  625. * @param array $message
  626. * @param string $query (since 1.2.5)
  627. * @param boolean $filter (since 1.4.1) see sqimap_fread()
  628. * @param mixed $outputstream (since 1.4.1) see sqimap_fread()
  629. * @param boolean $no_return (since 1.4.1) see sqimap_fread()
  630. */
  631. function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors,
  632. &$response, &$message, $query = '',
  633. $filter=false,$outputstream=false,$no_return=false) {
  634. $tag_uid_a = explode(' ',trim($tag_uid));
  635. $tag = $tag_uid_a[0];
  636. $res = sqimap_retrieve_imap_response($imap_stream, $tag, $handle_errors,
  637. $response, $message, $query,$filter,$outputstream,$no_return);
  638. return $res;
  639. }
  640. /**
  641. * Connects to the IMAP server and returns a resource identifier for use with
  642. * the other SquirrelMail IMAP functions. Does NOT login!
  643. * @param string server hostname of IMAP server
  644. * @param int port port number to connect to
  645. * @param integer $tls whether to use plain text(0), TLS(1) or STARTTLS(2) when connecting.
  646. * Argument was boolean before 1.5.1.
  647. * @param array $stream_options Stream context options, see config_local.php
  648. * for more details (OPTIONAL)
  649. * @return imap-stream resource identifier
  650. * @since 1.5.0 (usable only in 1.5.1 or later)
  651. */
  652. function sqimap_create_stream($server,$port,$tls=0,$stream_options=array()) {
  653. global $squirrelmail_language;
  654. if (strstr($server,':') && ! preg_match("/^\[.*\]$/",$server)) {
  655. // numerical IPv6 address must be enclosed in square brackets
  656. $server = '['.$server.']';
  657. }
  658. // NB: Using "ssl://" ensures the highest possible TLS version
  659. // will be negotiated with the server (whereas "tls://" only
  660. // uses TLS version 1.0)
  661. //
  662. if ($tls == 1) {
  663. if ((check_php_version(4,3)) and (extension_loaded('openssl'))) {
  664. if (function_exists('stream_socket_client')) {
  665. $server_address = 'ssl://' . $server . ':' . $port;
  666. $ssl_context = @stream_context_create($stream_options);
  667. $connect_timeout = ini_get('default_socket_timeout');
  668. // null timeout is broken
  669. if ($connect_timeout == 0)
  670. $connect_timeout = 15;
  671. $imap_stream = @stream_socket_client($server_address, $error_number, $error_string, $connect_timeout, STREAM_CLIENT_CONNECT, $ssl_context);
  672. } else {
  673. $imap_stream = @fsockopen('ssl://' . $server, $port, $error_number, $error_string, 15);
  674. }
  675. } else {
  676. require_once(SM_PATH . 'functions/display_messages.php');
  677. logout_error( sprintf(_("Error connecting to IMAP server: %s."), $server).
  678. '<br />'.
  679. _("TLS is enabled, but this version of PHP does not support TLS sockets, or is missing the openssl extension.").
  680. '<br /><br />'.
  681. _("Please contact your system administrator and report this error."),
  682. sprintf(_("Error connecting to IMAP server: %s."), $server));
  683. }
  684. } else {
  685. $imap_stream = @fsockopen($server, $port, $error_number, $error_string, 15);
  686. }
  687. /* Do some error correction */
  688. if (!$imap_stream) {
  689. set_up_language($squirrelmail_language, true);
  690. require_once(SM_PATH . 'functions/display_messages.php');
  691. logout_error( sprintf(_("Error connecting to IMAP server: %s."), $server).
  692. //FIXME: NO HTML IN CORE!
  693. "<br />\r\n$error_number : $error_string<br />\r\n",
  694. sprintf(_("Error connecting to IMAP server: %s."), $server) );
  695. exit;
  696. }
  697. $server_info = fgets ($imap_stream, 1024);
  698. /**
  699. * Implementing IMAP STARTTLS (rfc2595) in php 5.1.0+
  700. * http://www.php.net/stream-socket-enable-crypto
  701. */
  702. if ($tls === 2) {
  703. if (function_exists('stream_socket_enable_crypto')) {
  704. // check starttls capability, don't use cached capability version
  705. if (! sqimap_capability($imap_stream, 'STARTTLS', false)) {
  706. // imap server does not declare starttls support
  707. sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
  708. '','',
  709. _("IMAP STARTTLS is enabled in SquirrelMail configuration, but used IMAP server does not support STARTTLS."));
  710. exit;
  711. }
  712. // issue starttls command and check response
  713. sqimap_run_command($imap_stream, 'STARTTLS', false, $starttls_response, $starttls_message);
  714. // check response
  715. if ($starttls_response!='OK') {
  716. // starttls command failed
  717. sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
  718. 'STARTTLS',
  719. _("Server replied:") . ' ',
  720. $starttls_message);
  721. exit();
  722. }
  723. // start crypto on connection. suppress function errors.
  724. if (@stream_socket_enable_crypto($imap_stream,true,STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
  725. // starttls was successful
  726. /**
  727. * RFC 2595 requires to discard CAPABILITY information after successful
  728. * STARTTLS command. We don't follow RFC, because SquirrelMail stores CAPABILITY
  729. * information only after successful login (src/redirect.php) and cached information
  730. * is used only in other php script connections after successful STARTTLS. If script
  731. * issues sqimap_capability() call before sqimap_login() and wants to get initial
  732. * capability response, script should set third sqimap_capability() argument to false.
  733. */
  734. //sqsession_unregister('sqimap_capabilities');
  735. } else {
  736. /**
  737. * stream_socket_enable_crypto() call failed. Possible issues:
  738. * - broken ssl certificate (uw drops connection, error is in syslog mail facility)
  739. * - some ssl error (can reproduce with STREAM_CRYPTO_METHOD_SSLv3_CLIENT, PHP E_WARNING
  740. * suppressed in stream_socket_enable_crypto() call)
  741. */
  742. sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
  743. '','',
  744. _("Unable to start TLS."));
  745. /**
  746. * Bug: stream_socket_enable_crypto() does not register SSL errors in
  747. * openssl_error_string() or stream notification wrapper and displays
  748. * them in E_WARNING level message. It is impossible to retrieve error
  749. * message without own error handler.
  750. */
  751. exit;
  752. }
  753. } else {
  754. // php install does not support stream_socket_enable_crypto() function
  755. sqimap_error_box(sprintf(_("Error connecting to IMAP server: %s."), $server),
  756. '','',
  757. _("IMAP STARTTLS is enabled in SquirrelMail configuration, but used PHP version does not support functions that allow to enable encryption on open socket."));
  758. exit;
  759. }
  760. }
  761. return $imap_stream;
  762. }
  763. /**
  764. * Logs the user into the IMAP server. If $hide is set, no error messages
  765. * will be displayed (if set to 1, just exits, if set to 2, returns FALSE).
  766. * This function returns the IMAP connection handle.
  767. * @param string $username user name
  768. * @param string $password password encrypted with onetimepad. Since 1.5.2
  769. * function can use internal password functions, if parameter is set to
  770. * boolean false.
  771. * @param string $imap_server_address address of imap server
  772. * @param integer $imap_port port of imap server
  773. * @param int $hide controls display connection errors:
  774. * 0 = do not hide
  775. * 1 = show no errors (just exit)
  776. * 2 = show no errors (return FALSE)
  777. * 3 = show no errors (return error string)
  778. * @param array $stream_options Stream context options, see config_local.php
  779. * for more details (OPTIONAL)
  780. * @return mixed The IMAP connection stream, or if the connection fails,
  781. * FALSE if $hide is set to 2 or an error string if $hide
  782. * is set to 3.
  783. */
  784. function sqimap_login ($username, $password, $imap_server_address,
  785. $imap_port, $hide, $stream_options=array()) {
  786. global $color, $squirrelmail_language, $onetimepad, $use_imap_tls,
  787. $imap_auth_mech, $sqimap_capabilities, $display_imap_login_error;
  788. // Note/TODO: This hack grabs the $authz argument from the session. In the short future,
  789. // a new argument in function sqimap_login() will be used instead.
  790. $authz = '';
  791. global $authz;
  792. sqgetglobalvar('authz' , $authz , SQ_SESSION);
  793. if(!empty($authz)) {
  794. /* authz plugin - specific:
  795. * Get proxy login parameters from authz plugin configuration. If they
  796. * exist, they will override the current ones.
  797. * This is useful if we want to use different SASL authentication mechanism
  798. * and/or different TLS settings for proxy logins. */
  799. global $authz_imap_auth_mech, $authz_use_imap_tls, $authz_imapPort_tls;
  800. $imap_auth_mech = !empty($authz_imap_auth_mech) ? strtolower($authz_imap_auth_mech) : $imap_auth_mech;
  801. $use_imap_tls = !empty($authz_use_imap_tls)? $authz_use_imap_tls : $use_imap_tls;
  802. $imap_port = !empty($authz_use_imap_tls)? $authz_imapPort_tls : $imap_port;
  803. if($imap_auth_mech == 'login' || $imap_auth_mech == 'cram-md5') {
  804. logout_error("Misconfigured Plugin (authz or equivalent):<br/>".
  805. "The LOGIN and CRAM-MD5 authentication mechanisms cannot be used when attempting proxy login.");
  806. exit;
  807. }
  808. }
  809. /* get imap login password */
  810. if ($password===false) {
  811. /* standard functions */
  812. $password = sqauth_read_password();
  813. } else {
  814. /* old way. $key must be extracted from cookie */
  815. if (!isset($onetimepad) || empty($onetimepad)) {
  816. sqgetglobalvar('onetimepad' , $onetimepad , SQ_SESSION );
  817. }
  818. /* Decrypt the password */
  819. $password = OneTimePadDecrypt($password, $onetimepad);
  820. }
  821. if (!isset($sqimap_capabilities)) {
  822. sqgetglobalvar('sqimap_capabilities' , $sqimap_capabilities , SQ_SESSION );
  823. }
  824. $host = $imap_server_address;
  825. $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
  826. $imap_stream = sqimap_create_stream($imap_server_address,$imap_port,$use_imap_tls,$stream_options);
  827. if (substr($imap_auth_mech, 0, 6) == 'scram-') {
  828. // Doing SCRAM
  829. $hAlg = scram_supports(substr($imap_auth_mech, 6));
  830. if ($hAlg === false) {
  831. $response="BAD";
  832. $message='PHP server does not appear to support the authentication method selected.';
  833. $message .= ' Please contact your system administrator.';
  834. } else {
  835. $tag=sqimap_session_id(false);
  836. fputs($imap_stream, $tag.' AUTHENTICATE '.strtoupper($imap_auth_mech)."\r\n");
  837. $tmp = sqimap_fgets($imap_stream);
  838. if ($tmp[0] !== '+') {
  839. $response="BAD";
  840. $message='IMAP server does not appear to support the authentication method selected.';
  841. $message .= ' Please contact your system administrator.';
  842. } else {
  843. // No Channel Binding support...
  844. $cbf = 'n';
  845. // Generate 20 random bytes
  846. $cliNonce = scram_nonce();
  847. // Build SCRAM request
  848. $scram_request = scram_request($username, $cbf, $cliNonce);
  849. fputs($imap_stream, $scram_request."\r\n");
  850. // Get SCRAM response
  851. $tmp = sqimap_fgets($imap_stream);
  852. if ($tmp[0] !== '+'){
  853. $tmp = explode(' ', $tmp, 3);
  854. $response=$tmp[1];
  855. $message=$tmp[2];
  856. } else {
  857. // At this point, $tmp should hold "+ <challenge string>"
  858. $chall = substr($tmp,2);
  859. $serData = scram_parse_challenge($chall, $cliNonce);
  860. if ($serData === false) {
  861. $response="BAD";
  862. $message='IMAP server challenge could not be parsed.';
  863. $message .= ' Please contact your system administrator.';
  864. } else {
  865. $scram_response = scram_response($hAlg, $username, $cbf, $cliNonce, $serData['r'], $password, $serData['s'], $serData['i']);
  866. fputs($imap_stream, $scram_response."\r\n");
  867. // Get SCRAM validation
  868. $tmp = sqimap_fgets($imap_stream);
  869. if ($tmp[0] !== '+'){
  870. $tmp = explode(' ', $tmp, 3);
  871. $response=$tmp[1];
  872. $message=$tmp[2];
  873. } else {
  874. // At this point, $tmp should hold "+ <server verification string>"
  875. $serVer = substr($tmp,2);
  876. $valid = scram_verify($hAlg, $username, $cbf, $cliNonce, $serData['r'], $password, $serData['s'], $serData['i'], $serVer);
  877. if ($valid === false) {
  878. $response="BAD";
  879. $message='IMAP server challenge response could not be verified.';
  880. $message .= ' Please contact your system administrator.';
  881. } else {
  882. fputs($imap_stream, "\r\n");
  883. // Just to make sure we're really logged in
  884. $tmp = sqimap_fgets($imap_stream);
  885. $tmp = explode(' ', $tmp, 3);
  886. $response=$tmp[1];
  887. $message=$tmp[2];
  888. }
  889. }
  890. }
  891. }
  892. }
  893. }
  894. // SCRAM code ends here
  895. } else if (($imap_auth_mech == 'cram-md5') OR ($imap_auth_mech == 'digest-md5')) {
  896. // We're using some sort of authentication OTHER than plain or login
  897. $tag=sqimap_session_id(false);
  898. if ($imap_auth_mech == 'digest-md5') {
  899. $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
  900. } elseif ($imap_auth_mech == 'cram-md5') {
  901. $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
  902. }
  903. fputs($imap_stream,$query);
  904. $answer=sqimap_fgets($imap_stream);
  905. // Trim the "+ " off the front
  906. $response=explode(" ",$answer,3);
  907. if ($response[0] == '+') {
  908. // Got a challenge back
  909. $challenge=$response[1];
  910. if ($imap_auth_mech == 'digest-md5') {
  911. $reply = digest_md5_response($username,$password,$challenge,'imap',$host,$authz);
  912. } elseif ($imap_auth_mech == 'cram-md5') {
  913. $reply = cram_md5_response($username,$password,$challenge);
  914. }
  915. fputs($imap_stream,$reply);
  916. $read=sqimap_fgets($imap_stream);
  917. if ($imap_auth_mech == 'digest-md5') {
  918. // DIGEST-MD5 has an extra step..
  919. if (substr($read,0,1) == '+') { // OK so far..
  920. fputs($imap_stream,"\r\n");
  921. $read=sqimap_fgets($imap_stream);
  922. }
  923. }
  924. // IMAP server might return some untagged info before
  925. // the tagged login command response - skip over that
  926. while ($read[0] === '*') {
  927. $read = sqimap_fgets($imap_stream);
  928. }
  929. $results=explode(" ",$read,3);
  930. $response=$results[1];
  931. $message=$results[2];
  932. } else {
  933. // Fake the response, so the error trap at the bottom will work
  934. $response="BAD";
  935. $message='IMAP server does not appear to support the authentication method selected.';
  936. $message .= ' Please contact your system administrator.';
  937. }
  938. } elseif ($imap_auth_mech == 'login') {
  939. // Original IMAP login code
  940. $query = 'LOGIN "' . quoteimap($username) . '" "' . quoteimap($password) . '"';
  941. $read = sqimap_run_command ($imap_stream, $query, false, $response, $message);
  942. } elseif ($imap_auth_mech == 'plain') {
  943. /***
  944. * SASL PLAIN, RFC 4616 (updates 2595)
  945. *
  946. * The mechanism consists of a single message, a string of [UTF-8]
  947. * encoded [Unicode] characters, from the client to the server. The
  948. * client presents the authorization identity (identity to act as),
  949. * followed by a NUL (U+0000) character, followed by the authentication
  950. * identity (identity whose password will be used), followed by a NUL
  951. * (U+0000) character, followed by the clear-text password. As with
  952. * other SASL mechanisms, the client does not provide an authorization
  953. * identity when it wishes the server to derive an identity from the
  954. * credentials and use that as the authorization identity.
  955. */
  956. $tag=sqimap_session_id(false);
  957. $sasl = sqimap_capability($imap_stream, 'SASL-IR');
  958. if(!empty($authz)) {
  959. $auth = base64_encode("$username\0$authz\0$password");
  960. } else {
  961. $auth = base64_encode("$username\0$username\0$password");
  962. }
  963. if ($sasl) {
  964. // IMAP Extension for SASL Initial Client Response
  965. // <draft-siemborski-imap-sasl-initial-response-01b.txt>
  966. $query = $tag . " AUTHENTICATE PLAIN $auth\r\n";
  967. fputs($imap_stream, $query);
  968. $read = sqimap_fgets($imap_stream);
  969. } else {
  970. $query = $tag . " AUTHENTICATE PLAIN\r\n";
  971. fputs($imap_stream, $query);
  972. $read=sqimap_fgets($imap_stream);
  973. if (substr($read,0,1) == '+') { // OK so far..
  974. fputs($imap_stream, "$auth\r\n");
  975. $read = sqimap_fgets($imap_stream);
  976. }
  977. }
  978. // IMAP server might return some untagged info before
  979. // the tagged login command response - skip over that
  980. while ($read[0] === '*') {
  981. $read = sqimap_fgets($imap_stream);
  982. }
  983. $results=explode(" ",$read,3);
  984. $response=$results[1];
  985. $message=$results[2];
  986. } else {
  987. $response="BAD";
  988. $message="Internal SquirrelMail error - unknown IMAP authentication method chosen. Please contact the developers.";
  989. }
  990. /* If the connection was not successful, lets see why */
  991. if ($response != 'OK') {
  992. if (!$hide || $hide == 3) {
  993. //FIXME: UUURG... We don't want HTML in error messages, should also do html sanitizing of error messages elsewhere; should't assume output is destined for an HTML browser here
  994. if ($response != 'NO') {
  995. /* "BAD" and anything else gets reported here. */
  996. $message = sm_encode_html_special_chars($message);
  997. set_up_language($squirrelmail_language, true);
  998. if ($response == 'BAD') {
  999. if ($hide == 3) return sprintf(_("Bad request: %s"), $message);
  1000. $string = sprintf (_("Bad request: %s")."<br />\r\n", $message);
  1001. } else {
  1002. if ($hide == 3) return sprintf(_("Unknown error: %s"), $message);
  1003. $string = sprintf (_("Unknown error: %s") . "<br />\n", $message);
  1004. }
  1005. if (isset($read) && is_array($read)) {
  1006. $string .= '<br />' . _("Read data:") . "<br />\n";
  1007. foreach ($read as $line) {
  1008. $string .= sm_encode_html_special_chars($line) . "<br />\n";
  1009. }
  1010. }
  1011. error_box($string);
  1012. exit;
  1013. } else {
  1014. /*
  1015. * If the user does not log in with the correct
  1016. * username and password it is not possible to get the
  1017. * correct locale from the user's preferences.
  1018. * Therefore, apply the same hack as on the login
  1019. * screen.
  1020. *
  1021. * $squirrelmail_language is set by a cookie when
  1022. * the user selects language and logs out
  1023. */
  1024. set_up_language($squirrelmail_language, true);
  1025. sqsession_destroy();
  1026. /* terminate the session nicely */
  1027. sqimap_logout($imap_stream);
  1028. // determine what error message to use
  1029. //
  1030. $fail_msg = _("Unknown user or password incorrect.");
  1031. if ($display_imap_login_error) {
  1032. // See if there is an error message from the server
  1033. // Skip any rfc5530 response code: '[something]' at the
  1034. // start of the message
  1035. if (!empty($message)
  1036. && $message[0] == '['
  1037. && ($end = strstr($message, ']'))
  1038. && $end != ']') {
  1039. $message = substr($end, 1);
  1040. }
  1041. // Remove surrounding spaces and if there
  1042. // is anything left, display that as the
  1043. // error message:
  1044. $message = trim($message);
  1045. if (strlen($message))
  1046. $fail_msg = _($message);
  1047. }
  1048. if ($hide == 3) return $fail_msg;
  1049. logout_error($fail_msg);
  1050. exit;
  1051. }
  1052. } else {
  1053. if ($hide == 2) return FALSE;
  1054. exit;
  1055. }
  1056. }
  1057. /* Special error case:
  1058. * Login referrals. The server returns:
  1059. * ? OK [REFERRAL <imap url>]
  1060. * Check RFC 2221 for details. Since we do not support login referrals yet
  1061. * we log the user out.
  1062. */
  1063. if ( stristr($message, 'REFERRAL imap') === TRUE ) {
  1064. sqimap_logout($imap_stream);
  1065. set_up_language($squirrelmail_language, true);
  1066. sqsession_destroy();
  1067. logout_error( _("Your mailbox is not located at this server. Try a different server or consult your system administrator") );
  1068. exit;
  1069. }
  1070. // Run ID command if configured - RFC 2971
  1071. //
  1072. // Administrator must declare a configuration variable called
  1073. // $imap_id_command_args in config/config_local.php which must
  1074. // be an array, where each key is an attibute to be sent in the
  1075. // IMAP ID command to the server. Values will be sent as-is
  1076. // except if the value is "###REMOTE ADDRESS###" (without quotes)
  1077. // in which case the current user's real IP address will be
  1078. // substituted. If "###X-FORWARDED-FOR###" is used and a
  1079. // "X-FORWARDED-FOR" header is present in the client request,
  1080. // the contents of that header are used (careful, this can be
  1081. // forged). If "###X-FORWARDED-FOR OR REMOTE ADDRESS###" is
  1082. // used, then the "X-FORWARDED-FOR" header is used if it is
  1083. // present in the request, otherwise, the client's connecting
  1084. // IP address is used. The following attributes will always be
  1085. // added unless they are specifically overridden with a blank
  1086. // value:
  1087. // name, vendor, support-url, version
  1088. // A parsed representation of server's response is made available
  1089. // to plugins as both a global and session variable named
  1090. // "imap_server_id_response" (a simple key/value array) unless
  1091. // response parsing is turned off by way of setting a variable
  1092. // named $do_not_parse_imap_id_command_response in
  1093. // config/config_local.php to TRUE, in which case, the stored
  1094. // response will be the unparsed IMAP response.
  1095. //
  1096. global $imap_id_command_args, $do_not_parse_imap_id_command_response;
  1097. if (!empty($imap_id_command_args) && is_array($imap_id_command_args)
  1098. && sqimap_capability($imap_stream, 'ID')) {
  1099. static $args = array();
  1100. if (empty($args)) {
  1101. if (!isset($imap_id_command_args['name']))
  1102. $imap_id_command_args['name'] = 'SquirrelMail';
  1103. if (!isset($imap_id_command_args['vendor']))
  1104. $imap_id_command_args['vendor'] = 'SquirrelMail Project Team';
  1105. if (!isset($imap_id_command_args['support-url']))
  1106. $imap_id_command_args['support-url'] = 'https://squirrelmail.org';
  1107. if (!isset($imap_id_command_args['version'])) {
  1108. $imap_id_command_args['version'] = SM_VERSION;
  1109. }
  1110. foreach ($imap_id_command_args as $key => $value) {
  1111. $key = trim($key);
  1112. $value = trim($value);
  1113. if ($key === '' || $value === '')
  1114. continue;
  1115. if ($value === '###REMOTE ADDRESS###' && sqGetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER))
  1116. $value = $remote_addr;
  1117. else if ($value === '###X-FORWARDED-FOR###' && sqGetGlobalVar('HTTP_X_FORWARDED_FOR', $remote_addr, SQ_SERVER))
  1118. $value = $remote_addr;
  1119. else if ($value === '###X-FORWARDED-FOR OR REMOTE ADDRESS###') {
  1120. if (sqGetGlobalVar('HTTP_X_FORWARDED_FOR', $remote_addr, SQ_SERVER))
  1121. $value = $remote_addr;
  1122. else if (sqGetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER))
  1123. $value = $remote_addr;
  1124. }
  1125. else if ($value === '###REMOTE ADDRESS###' && sqGetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER)) {
  1126. $value = $remote_addr;
  1127. }
  1128. $args[] = '"' . str_replace(array('"', '\\'), array('\\"', '\\\\'), $key)
  1129. . '" "' . str_replace(array('"', '\\'), array('\\"', '\\\\'), $value) . '"';
  1130. }
  1131. }
  1132. $read_ary = sqimap_run_command($imap_stream, 'ID (' . implode(' ', $args) . ')', false, $response, $message);
  1133. if (!empty($read_ary) && is_array($read_ary)) {
  1134. global $imap_server_id_response;
  1135. if ($do_not_parse_imap_id_command_response)
  1136. $imap_server_id_response = $read_ary;
  1137. else
  1138. {
  1139. $imap_server_id_response = array();
  1140. // NOTE that this parser ignores closing ) sign, so
  1141. // technically some kind of malformed server
  1142. // response could cause extra junk to be included here
  1143. foreach ($read_ary as $info)
  1144. {
  1145. $parsed_info = explode('(', $info, 2);
  1146. if (!empty($parsed_info[1]))
  1147. {
  1148. // find opening quote for the next key name
  1149. while ($parsed_info = explode('"', $parsed_info[1], 2))
  1150. {
  1151. if (empty($parsed_info[1]))
  1152. break;
  1153. else
  1154. {
  1155. // find closing quote for the key name
  1156. $pos = strpos($parsed_info[1], '"');
  1157. if ($pos === FALSE)
  1158. break;
  1159. else
  1160. {
  1161. $key = substr($parsed_info[1], 0, $pos);
  1162. $parsed_info[1] = substr($parsed_info[1], $pos + 1);
  1163. // find opening quote for the key's value
  1164. $parsed_info = explode('"', $parsed_info[1], 2);
  1165. if (empty($parsed_info[1]))
  1166. break;
  1167. else
  1168. {
  1169. // find closing quote for the key's value
  1170. $pos = strpos($parsed_info[1], '"');
  1171. if ($pos === FALSE)
  1172. break;
  1173. else
  1174. {
  1175. $imap_server_id_response[$key] = substr($parsed_info[1], 0, $pos);
  1176. $parsed_info[1] = substr($parsed_info[1], $pos + 1);
  1177. }
  1178. }
  1179. }
  1180. }
  1181. }
  1182. }
  1183. }
  1184. }
  1185. sqsession_register($imap_server_id_response, 'imap_server_id_response');
  1186. }
  1187. }
  1188. return $imap_stream;
  1189. }
  1190. /**
  1191. * Simply logs out the IMAP session
  1192. * @param stream $imap_stream the IMAP connection to log out.
  1193. * @return void
  1194. */
  1195. function sqimap_logout ($imap_stream) {
  1196. /* Logout is not valid until the server returns 'BYE'
  1197. * If we don't have an imap_ stream we're already logged out */
  1198. if(isset($imap_stream) && $imap_stream) {
  1199. sqimap_run_command($imap_stream, 'LOGOUT', false, $response, $message);
  1200. fclose($imap_stream);
  1201. }
  1202. }
  1203. /**
  1204. * Retrieve the CAPABILITY string from the IMAP server.
  1205. * If capability is set, returns only that specific capability,
  1206. * else returns array of all capabilities.
  1207. * @param stream $imap_stream
  1208. * @param string $capability (since 1.3.0)
  1209. * @param boolean $bUseCache (since 1.5.1) Controls use of capability data stored in session
  1210. * @return mixed (string or array if $capability is set and found (array in the case the capability has multiple options),
  1211. * false, if $capability is set and not found,
  1212. * array if $capability not set)
  1213. */
  1214. function sqimap_capability($imap_stream, $capability='', $bUseCache=true) {
  1215. // sqgetGlobalVar('sqimap_capabilities', $sqimap_capabilities, SQ_SESSION);
  1216. if (!$bUseCache || ! sqgetGlobalVar('sqimap_capabilities', $sqimap_capabilities, SQ_SESSION)) {
  1217. $sqimap_capabilities = array();
  1218. $read = sqimap_run_command($imap_stream, 'CAPABILITY', true, $a, $b);
  1219. $c = explode(' ', $read[0]);
  1220. for ($i=2; $i < count($c); $i++) {
  1221. $cap_list = explode('=', $c[$i]);
  1222. if (isset($cap_list[1])) {
  1223. if(isset($sqimap_capabilities[trim($cap_list[0])]) &&
  1224. !is_array($sqimap_capabilities[trim($cap_list[0])])) {
  1225. // Remove array key that was added in 'else' block below
  1226. // This is to accomodate for capabilities like:
  1227. // SORT SORT=MODSEQ
  1228. unset($sqimap_capabilities[trim($cap_list[0])]);
  1229. }
  1230. $sqimap_capabilities[trim($cap_list[0])][] = $cap_list[1];
  1231. } else {
  1232. if(!isset($sqimap_capabilities[trim($cap_list[0])])) {
  1233. $sqimap_capabilities[trim($cap_list[0])] = TRUE;
  1234. }
  1235. }
  1236. }
  1237. }
  1238. if ($capability) {
  1239. if (isset($sqimap_capabilities[$capability])) {
  1240. return $sqimap_capabilities[$capability];
  1241. } else {
  1242. return false;
  1243. }
  1244. }
  1245. return $sqimap_capabilities;
  1246. }
  1247. /**
  1248. * Returns the delimiter between mailboxes: INBOX/Test, or INBOX.Test
  1249. * @param stream $imap_stream
  1250. * @return string
  1251. */
  1252. function sqimap_get_delimiter ($imap_stream = false) {
  1253. global $sqimap_delimiter, $optional_delimiter;
  1254. /* Use configured delimiter if set */
  1255. if((!empty($optional_delimiter)) && $optional_delimiter != 'detect') {
  1256. return $optional_delimiter;
  1257. }
  1258. /* Delimiter is stored in the session from redirect. Try fetching from there first */
  1259. if (empty($sqimap_delimiter)) {
  1260. sqgetGlobalVar('delimiter',$sqimap_delimiter,SQ_SESSION);
  1261. }
  1262. /* Do some caching here */
  1263. if (!$sqimap_delimiter) {
  1264. if (sqimap_capability($imap_stream, 'NAMESPACE')
  1265. /*
  1266. * According to something that I can't find, this is supposed to work on all systems
  1267. * OS: This won't work in Courier IMAP.
  1268. * OS: According to rfc2342 response from NAMESPACE command is:
  1269. * OS: * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS NAMESPACE) (SHARED NAMESPACES)
  1270. * OS: We want to lookup all personal NAMESPACES...
  1271. *
  1272. * TODO: remove this in favour of the information from sqimap_get_namespace()
  1273. */
  1274. && ($read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b))
  1275. && preg_match('/\* NAMESPACE +(\( *\(.+\) *\)|NIL) +(\( *\(.+\) *\)|NIL) +(\( *\(.+\) *\)|NIL)/i', $read[0], $data)
  1276. && preg_match('/^\( *\((.*)\) *\)/', $data[1], $data2)) {
  1277. $pn = $data2[1];
  1278. $pna = explode(')(', $pn);
  1279. $delnew = array();
  1280. foreach ($pna as $v) {
  1281. $lst = explode('"', $v);
  1282. if (isset($lst[3])) {
  1283. $delnew[$lst[1]] = $lst[3];
  1284. } else {
  1285. $delnew[$lst[1]] = '';
  1286. }
  1287. }
  1288. $sqimap_delimiter = array_shift($delnew);
  1289. } else {
  1290. fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
  1291. $read = sqimap_read_data($imap_stream, '.', true, $a, $b);
  1292. $read = $read['.'][0]; //sqimap_read_data() now returns a tag array of response array
  1293. $quote_position = strpos ($read[0], '"');
  1294. $sqimap_delimiter = substr ($read[0], $quote_position+1, 1);
  1295. }
  1296. }
  1297. return $sqimap_delimiter;
  1298. }
  1299. /**
  1300. * Retrieves the namespaces from the IMAP server.
  1301. * NAMESPACE is an IMAP extension defined in RFC 2342.
  1302. *
  1303. * @param stream $imap_stream
  1304. * @return array
  1305. */
  1306. function sqimap_get_namespace($imap_stream) {
  1307. $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
  1308. return sqimap_parse_namespace($read[0]);
  1309. }
  1310. /**
  1311. * Parses a NAMESPACE response and returns an array with the available
  1312. * personal, users and shared namespaces.
  1313. *
  1314. * @param string $input
  1315. * @return array The returned array has the following format:
  1316. * <pre>
  1317. * array(
  1318. * 'personal' => array(
  1319. * 0 => array('prefix'=>'INBOX.','delimiter' =>'.'),
  1320. * 1 => ...
  1321. * ),
  1322. * 'users' => array(..
  1323. * ),
  1324. * 'shared' => array( ..
  1325. * )
  1326. * )
  1327. * </pre>
  1328. * Note that if a namespace is not defined in the server, then the corresponding
  1329. * array will be empty.
  1330. */
  1331. function sqimap_parse_namespace(&$input) {
  1332. $ns_strings = array(1=>'personal', 2=>'users', 3=>'shared');
  1333. $namespace = array();
  1334. if (preg_match('/NAMESPACE (\(\(.*\)\)|NIL) (\(\(.*\)\)|NIL) (\(\(.*\)\)|NIL)/', $input, $regs)) {
  1335. for($i=1; $i<=3; $i++) {
  1336. if($regs[$i] == 'NIL') {
  1337. $namespace[$ns_strings[$i]] = array();
  1338. } else {
  1339. // Pop-out the first ( and last ) for easier parsing
  1340. $ns = substr($regs[$i], 1, -1);
  1341. if($c = preg_match_all('/\((?:(.*?)\s*?)\)/', $ns, $regs2)) {
  1342. $namespace[$ns_strings[$i]] = array();
  1343. for($j=0; $j<sizeof($regs2[1]); $j++) {
  1344. preg_match('/"(.*)"\s+("(.*)"|NIL)/', $regs2[1][$j], $regs3);
  1345. $namespace[$ns_strings[$i]][$j]['prefix'] = $regs3[1];
  1346. if($regs3[2] == 'NIL') {
  1347. $namespace[$ns_strings[$i]][$j]['delimiter'] = null;
  1348. } else {
  1349. // $regs[3] is $regs[2] without the quotes
  1350. $namespace[$ns_strings[$i]][$j]['delimiter'] = $regs3[3];
  1351. }
  1352. unset($regs3);
  1353. }
  1354. }
  1355. unset($ns);
  1356. }
  1357. }
  1358. }
  1359. return($namespace);
  1360. }
  1361. /**
  1362. * This encodes a mailbox name for use in IMAP commands.
  1363. * @param string $what the mailbox to encode
  1364. * @return string the encoded mailbox string
  1365. * @since 1.5.0
  1366. */
  1367. function sqimap_encode_mailbox_name($what)
  1368. {
  1369. if (preg_match('/["\\\r\n]/', $what))
  1370. return '{' . strlen($what) . "}\r\n" . $what; /* 4.3 literal form */
  1371. return '"' . $what . '"'; /* 4.3 quoted string form */
  1372. }
  1373. /**
  1374. * Gets the number of messages in the current mailbox.
  1375. *
  1376. * OBSOLETE use sqimap_status_messages instead.
  1377. * @param stream $imap_stream imap stream
  1378. * @param string $mailbox
  1379. * @deprecated
  1380. */
  1381. function sqimap_get_num_messages ($imap_stream, $mailbox) {
  1382. $aStatus = sqimap_status_messages($imap_stream,$mailbox,array('MESSAGES'));
  1383. return $aStatus['MESSAGES'];
  1384. }
  1385. /**
  1386. * OBSOLETE FUNCTION should be removed after mailbox_display,
  1387. * printMessage function is adapted
  1388. * $addr_ar = array(), $group = '' and $host='' arguments are used in 1.4.0
  1389. * @param string $address
  1390. * @param integer $max
  1391. * @since 1.4.0
  1392. * @deprecated See Rfc822Address.php
  1393. */
  1394. function parseAddress($address, $max=0) {
  1395. $aAddress = parseRFC822Address($address,array('limit'=> $max));
  1396. /*
  1397. * Because the expected format of the array element is changed we adapt it now.
  1398. * This also implies that this function is obsolete and should be removed after the
  1399. * rest of the source is adapted. See Rfc822Address.php for the new function.
  1400. */
  1401. array_walk($aAddress, '_adaptAddress');
  1402. return $aAddress;
  1403. }
  1404. /**
  1405. * OBSOLETE FUNCTION should be removed after mailbox_display,
  1406. * printMessage function is adapted
  1407. *
  1408. * callback function used for formating of addresses array in
  1409. * parseAddress() function
  1410. * @param array $aAddr
  1411. * @param integer $k array key
  1412. * @since 1.5.1
  1413. * @deprecated
  1414. */
  1415. function _adaptAddress(&$aAddr,$k) {
  1416. $sPersonal = (isset($aAddr[SQM_ADDR_PERSONAL]) && $aAddr[SQM_ADDR_PERSONAL]) ?
  1417. $aAddr[SQM_ADDR_PERSONAL] : '';
  1418. $sEmail = ($aAddr[SQM_ADDR_HOST]) ?
  1419. $aAddr[SQM_ADDR_MAILBOX] . '@'.$aAddr[SQM_ADDR_HOST] :
  1420. $aAddr[SQM_ADDR_MAILBOX];
  1421. $aAddr = array($sEmail,$sPersonal);
  1422. }
  1423. /**
  1424. * Returns the number of unseen messages in this folder.
  1425. * obsoleted by sqimap_status_messages !
  1426. * Arguments differ in 1.0.x
  1427. * @param stream $imap_stream
  1428. * @param string $mailbox
  1429. * @return integer
  1430. * @deprecated
  1431. */
  1432. function sqimap_unseen_messages ($imap_stream, $mailbox) {
  1433. $aStatus = sqimap_status_messages($imap_stream,$mailbox,array('UNSEEN'));
  1434. return $aStatus['UNSEEN'];
  1435. }
  1436. /**
  1437. * Returns the status items of a mailbox.
  1438. * Default it returns MESSAGES,UNSEEN and RECENT
  1439. * Supported status items are MESSAGES, UNSEEN, RECENT (since 1.4.0),
  1440. * UIDNEXT (since 1.5.1) and UIDVALIDITY (since 1.5.1)
  1441. * @param stream $imap_stream imap stream
  1442. * @param string $mailbox mail folder
  1443. * @param array $aStatusItems status items
  1444. * @return array
  1445. * @since 1.3.2
  1446. */
  1447. function sqimap_status_messages ($imap_stream, $mailbox,
  1448. $aStatusItems = array('MESSAGES','UNSEEN','RECENT')) {
  1449. $aStatusItems = implode(' ',$aStatusItems);
  1450. $read_ary = sqimap_run_command ($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) .
  1451. " ($aStatusItems)", false, $result, $message);
  1452. $i = 0;
  1453. $messages = $unseen = $recent = $uidnext = $uidvalidity = false;
  1454. $regs = array(false,false);
  1455. while (isset($read_ary[$i])) {
  1456. if (preg_match('/UNSEEN\s+([0-9]+)/i', $read_ary[$i], $regs)) {
  1457. $unseen = $regs[1];
  1458. }
  1459. if (preg_match('/MESSAGES\s+([0-9]+)/i', $read_ary[$i], $regs)) {
  1460. $messages = $regs[1];
  1461. }
  1462. if (preg_match('/RECENT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
  1463. $recent = $regs[1];
  1464. }
  1465. if (preg_match('/UIDNEXT\s+([0-9]+)/i', $read_ary[$i], $regs)) {
  1466. $uidnext = $regs[1];
  1467. }
  1468. if (preg_match('/UIDVALIDITY\s+([0-9]+)/i', $read_ary[$i], $regs)) {
  1469. $uidvalidity = $regs[1];
  1470. }
  1471. $i++;
  1472. }
  1473. $status=array('MESSAGES' => $messages,
  1474. 'UNSEEN'=>$unseen,
  1475. 'RECENT' => $recent,
  1476. 'UIDNEXT' => $uidnext,
  1477. 'UIDVALIDITY' => $uidvalidity);
  1478. if (!empty($messages)) { $hook_status['MESSAGES']=$messages; }
  1479. if (!empty($unseen)) { $hook_status['UNSEEN']=$unseen; }
  1480. if (!empty($recent)) { $hook_status['RECENT']=$recent; }
  1481. if (!empty($hook_status)) {
  1482. $hook_status['MAILBOX']=$mailbox;
  1483. $hook_status['CALLER']='sqimap_status_messages';
  1484. do_hook('folder_status', $hook_status);
  1485. }
  1486. return $status;
  1487. }
  1488. /**
  1489. * Saves a message to a given folder -- used for saving sent messages
  1490. * @param stream $imap_stream
  1491. * @param string $sent_folder
  1492. * @param $length
  1493. * @return string $sid
  1494. */
  1495. function sqimap_append ($imap_stream, $sMailbox, $length) {
  1496. $sid = sqimap_session_id();
  1497. $query = $sid . ' APPEND ' . sqimap_encode_mailbox_name($sMailbox) . " (\\Seen) {".$length."}";
  1498. fputs ($imap_stream, "$query\r\n");
  1499. $tmp = fgets ($imap_stream, 1024);
  1500. sqimap_append_checkresponse($tmp, $sMailbox,$sid, $query);
  1501. return $sid;
  1502. }
  1503. /**
  1504. * @param stream imap_stream
  1505. * @param string $folder (since 1.3.2)
  1506. */
  1507. function sqimap_append_done ($imap_stream, $sMailbox='') {
  1508. fputs ($imap_stream, "\r\n");
  1509. $tmp = fgets ($imap_stream, 1024);
  1510. while (!sqimap_append_checkresponse($tmp, $sMailbox)) {
  1511. $tmp = fgets ($imap_stream, 1024);
  1512. }
  1513. }
  1514. /**
  1515. * Displays error messages, if there are errors in responses to
  1516. * commands issues by sqimap_append() and sqimap_append_done() functions.
  1517. * @param string $response
  1518. * @param string $sMailbox
  1519. * @return bool $bDone
  1520. * @since 1.5.1 and 1.4.5
  1521. */
  1522. function sqimap_append_checkresponse($response, $sMailbox, $sid='', $query='') {
  1523. // static vars to keep them available when sqimap_append_done calls this function.
  1524. static $imapquery, $imapsid;
  1525. $bDone = false;
  1526. if ($query) {
  1527. $imapquery = $query;
  1528. }
  1529. if ($sid) {
  1530. $imapsid = $sid;
  1531. }
  1532. if ($response[0] == '+') {
  1533. // continuation request triggerd by sqimap_append()
  1534. $bDone = true;
  1535. } else {
  1536. $i = strpos($response, ' ');
  1537. $sRsp = substr($response,0,$i);
  1538. $sMsg = substr($response,$i+1);
  1539. $aExtra = array('MAILBOX' => $sMailbox);
  1540. switch ($sRsp) {
  1541. case '*': //untagged response
  1542. $i = strpos($sMsg, ' ');
  1543. $sRsp = strtoupper(substr($sMsg,0,$i));
  1544. $sMsg = substr($sMsg,$i+1);
  1545. if ($sRsp == 'NO' || $sRsp == 'BAD') {
  1546. // for the moment disabled. Enable after 1.5.1 release.
  1547. // Notices could give valueable information about the mailbox
  1548. // Update: seems this was forgotten, but now it is finally enabled
  1549. sqm_trigger_imap_error('SQM_IMAP_APPEND_NOTICE',$imapquery,$sRsp,$sMsg);
  1550. }
  1551. $bDone = false;
  1552. case $imapsid:
  1553. // A001 OK message
  1554. // $imapsid<space>$sRsp<space>$sMsg
  1555. $bDone = true;
  1556. $i = strpos($sMsg, ' ');
  1557. $sRsp = strtoupper(substr($sMsg,0,$i));
  1558. $sMsg = substr($sMsg,$i+1);
  1559. switch ($sRsp) {
  1560. case 'NO':
  1561. if (preg_match("/(.*)(quota)(.*)$/i", $sMsg, $aMatch)) {
  1562. sqm_trigger_imap_error('SQM_IMAP_APPEND_QUOTA_ERROR',$imapquery,$sRsp,$sMsg,$aExtra);
  1563. } else {
  1564. sqm_trigger_imap_error('SQM_IMAP_APPEND_ERROR',$imapquery,$sRsp,$sMsg,$aExtra);
  1565. }
  1566. break;
  1567. case 'BAD':
  1568. sqm_trigger_imap_error('SQM_IMAP_ERROR',$imapquery,$sRsp,$sMsg,$aExtra);
  1569. break;
  1570. case 'BYE':
  1571. sqm_trigger_imap_error('SQM_IMAP_BYE',$imapquery,$sRsp,$sMsg,$aExtra);
  1572. break;
  1573. case 'OK':
  1574. break;
  1575. default:
  1576. break;
  1577. }
  1578. break;
  1579. default:
  1580. // should be false because of the unexpected response but i'm not sure if
  1581. // that will cause an endless loop in sqimap_append_done
  1582. $bDone = true;
  1583. }
  1584. }
  1585. return $bDone;
  1586. }
  1587. /**
  1588. * Allows mapping of IMAP server address with custom function
  1589. * see map_yp_alias()
  1590. * @param string $imap_server imap server address or mapping
  1591. * @param string $username
  1592. * @return string
  1593. * @since 1.3.0
  1594. */
  1595. function sqimap_get_user_server ($imap_server, $username) {
  1596. if (substr($imap_server, 0, 4) != "map:") {
  1597. return $imap_server;
  1598. }
  1599. $function = substr($imap_server, 4);
  1600. return $function($username);
  1601. }
  1602. /**
  1603. * This is an example that gets IMAP servers from yellowpages (NIS).
  1604. * you can simple put map:map_yp_alias in your $imap_server_address
  1605. * in config.php use your own function instead map_yp_alias to map your
  1606. * LDAP whatever way to find the users IMAP server.
  1607. *
  1608. * Requires access to external ypmatch program
  1609. * FIXME: it can be implemented in php yp extension or pecl (since php 5.1.0)
  1610. * @param string $username
  1611. * @return string
  1612. * @since 1.3.0
  1613. */
  1614. function map_yp_alias($username) {
  1615. $safe_username = escapeshellarg($username);
  1616. $yp = `ypmatch $safe_username aliases`;
  1617. return chop(substr($yp, strlen($username)+1));
  1618. }