imap_general.php 55 KB

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