strings.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. <?php
  2. /**
  3. * strings.php
  4. *
  5. * Copyright (c) 1999-2004 The SquirrelMail Project Team
  6. * Licensed under the GNU GPL. For full terms see the file COPYING.
  7. *
  8. * This code provides various string manipulation functions that are
  9. * used by the rest of the Squirrelmail code.
  10. *
  11. * @version $Id$
  12. * @package squirrelmail
  13. */
  14. /**
  15. * SquirrelMail version number -- DO NOT CHANGE
  16. */
  17. global $version;
  18. $version = '1.5.1 [CVS]';
  19. /**
  20. * SquirrelMail internal version number -- DO NOT CHANGE
  21. * $sm_internal_version = array (release, major, minor)
  22. */
  23. global $SQM_INTERNAL_VERSION;
  24. $SQM_INTERNAL_VERSION = array(1,5,1);
  25. /**
  26. * There can be a circular issue with includes, where the $version string is
  27. * referenced by the include of global.php, etc. before it's defined.
  28. * For that reason, bring in global.php AFTER we define the version strings.
  29. */
  30. require_once(SM_PATH . 'functions/global.php');
  31. /**
  32. * Wraps text at $wrap characters
  33. *
  34. * Has a problem with special HTML characters, so call this before
  35. * you do character translation.
  36. *
  37. * Specifically, &#039 comes up as 5 characters instead of 1.
  38. * This should not add newlines to the end of lines.
  39. *
  40. * @param string line the line of text to wrap, by ref
  41. * @param int wrap the maximum line lenth
  42. * @return void
  43. */
  44. function sqWordWrap(&$line, $wrap) {
  45. global $languages, $squirrelmail_language;
  46. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  47. function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
  48. if (mb_detect_encoding($line) != 'ASCII') {
  49. $line = $languages[$squirrelmail_language]['XTRA_CODE']('wordwrap', $line, $wrap);
  50. return;
  51. }
  52. }
  53. ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
  54. $beginning_spaces = $regs[1];
  55. if (isset($regs[2])) {
  56. $words = explode(' ', $regs[2]);
  57. } else {
  58. $words = '';
  59. }
  60. $i = 0;
  61. $line = $beginning_spaces;
  62. while ($i < count($words)) {
  63. /* Force one word to be on a line (minimum) */
  64. $line .= $words[$i];
  65. $line_len = strlen($beginning_spaces) + strlen($words[$i]) + 2;
  66. if (isset($words[$i + 1]))
  67. $line_len += strlen($words[$i + 1]);
  68. $i ++;
  69. /* Add more words (as long as they fit) */
  70. while ($line_len < $wrap && $i < count($words)) {
  71. $line .= ' ' . $words[$i];
  72. $i++;
  73. if (isset($words[$i]))
  74. $line_len += strlen($words[$i]) + 1;
  75. else
  76. $line_len += 1;
  77. }
  78. /* Skip spaces if they are the first thing on a continued line */
  79. while (!isset($words[$i]) && $i < count($words)) {
  80. $i ++;
  81. }
  82. /* Go to the next line if we have more to process */
  83. if ($i < count($words)) {
  84. $line .= "\n";
  85. }
  86. }
  87. }
  88. /**
  89. * Does the opposite of sqWordWrap()
  90. * @param string body the text to un-wordwrap
  91. * @return void
  92. */
  93. function sqUnWordWrap(&$body) {
  94. global $squirrelmail_language;
  95. if ($squirrelmail_language == 'ja_JP') {
  96. return;
  97. }
  98. $lines = explode("\n", $body);
  99. $body = '';
  100. $PreviousSpaces = '';
  101. $cnt = count($lines);
  102. for ($i = 0; $i < $cnt; $i ++) {
  103. preg_match("/^([\t >]*)([^\t >].*)?$/", $lines[$i], $regs);
  104. $CurrentSpaces = $regs[1];
  105. if (isset($regs[2])) {
  106. $CurrentRest = $regs[2];
  107. } else {
  108. $CurrentRest = '';
  109. }
  110. if ($i == 0) {
  111. $PreviousSpaces = $CurrentSpaces;
  112. $body = $lines[$i];
  113. } else if (($PreviousSpaces == $CurrentSpaces) /* Do the beginnings match */
  114. && (strlen($lines[$i - 1]) > 65) /* Over 65 characters long */
  115. && strlen($CurrentRest)) { /* and there's a line to continue with */
  116. $body .= ' ' . $CurrentRest;
  117. } else {
  118. $body .= "\n" . $lines[$i];
  119. $PreviousSpaces = $CurrentSpaces;
  120. }
  121. }
  122. $body .= "\n";
  123. }
  124. /**
  125. * If $haystack is a full mailbox name and $needle is the mailbox
  126. * separator character, returns the last part of the mailbox name.
  127. *
  128. * @param string haystack full mailbox name to search
  129. * @param string needle the mailbox separator character
  130. * @return string the last part of the mailbox name
  131. */
  132. function readShortMailboxName($haystack, $needle) {
  133. if ($needle == '') {
  134. $elem = $haystack;
  135. } else {
  136. $parts = explode($needle, $haystack);
  137. $elem = array_pop($parts);
  138. while ($elem == '' && count($parts)) {
  139. $elem = array_pop($parts);
  140. }
  141. }
  142. return( $elem );
  143. }
  144. /**
  145. * php_self
  146. *
  147. * Creates an URL for the page calling this function, using either the PHP global
  148. * REQUEST_URI, or the PHP global PHP_SELF with QUERY_STRING added.
  149. *
  150. * @return string the complete url for this page
  151. */
  152. function php_self () {
  153. if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER) && !empty($req_uri) ) {
  154. return $req_uri;
  155. }
  156. if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER) && !empty($php_self) ) {
  157. // need to add query string to end of PHP_SELF to match REQUEST_URI
  158. //
  159. if ( sqgetGlobalVar('QUERY_STRING', $query_string, SQ_SERVER) && !empty($query_string) ) {
  160. $php_self .= '?' . $query_string;
  161. }
  162. return $php_self;
  163. }
  164. return '';
  165. }
  166. /**
  167. * get_location
  168. *
  169. * Determines the location to forward to, relative to your server.
  170. * This is used in HTTP Location: redirects.
  171. * If this doesnt work correctly for you (although it should), you can
  172. * remove all this code except the last two lines, and have it return
  173. * the right URL for your site, something like:
  174. *
  175. * http://www.example.com/squirrelmail/
  176. *
  177. * @return string the base url for this SquirrelMail installation
  178. */
  179. function get_location () {
  180. global $imap_server_type;
  181. /* Get the path, handle virtual directories */
  182. if(strpos(php_self(), '?')) {
  183. $path = substr(php_self(), 0, strpos(php_self(), '?'));
  184. } else {
  185. $path = php_self();
  186. }
  187. $path = substr($path, 0, strrpos($path, '/'));
  188. if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
  189. return $full_url . $path;
  190. }
  191. /* Check if this is a HTTPS or regular HTTP request. */
  192. $proto = 'http://';
  193. /*
  194. * If you have 'SSLOptions +StdEnvVars' in your apache config
  195. * OR if you have HTTPS=on in your HTTP_SERVER_VARS
  196. * OR if you are on port 443
  197. */
  198. $getEnvVar = getenv('HTTPS');
  199. if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
  200. (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER) && !strcasecmp($https_on, 'on')) ||
  201. (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER) && $server_port == 443)) {
  202. $proto = 'https://';
  203. }
  204. /* Get the hostname from the Host header or server config. */
  205. if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
  206. if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
  207. $host = '';
  208. }
  209. }
  210. $port = '';
  211. if (! strstr($host, ':')) {
  212. if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
  213. if (($server_port != 80 && $proto == 'http://') ||
  214. ($server_port != 443 && $proto == 'https://')) {
  215. $port = sprintf(':%d', $server_port);
  216. }
  217. }
  218. }
  219. /* this is a workaround for the weird macosx caching that
  220. causes Apache to return 16080 as the port number, which causes
  221. SM to bail */
  222. if ($imap_server_type == 'macosx' && $port == ':16080') {
  223. $port = '';
  224. }
  225. /* Fallback is to omit the server name and use a relative */
  226. /* URI, although this is not RFC 2616 compliant. */
  227. $full_url = ($host ? $proto . $host . $port : '');
  228. sqsession_register($full_url, 'sq_base_url');
  229. return $full_url . $path;
  230. }
  231. /**
  232. * Encrypts password
  233. *
  234. * These functions are used to encrypt the password before it is
  235. * stored in a cookie. The encryption key is generated by
  236. * OneTimePadCreate();
  237. *
  238. * @param string string the (password)string to encrypt
  239. * @param string epad the encryption key
  240. * @return string the base64-encoded encrypted password
  241. */
  242. function OneTimePadEncrypt ($string, $epad) {
  243. $pad = base64_decode($epad);
  244. $encrypted = '';
  245. for ($i = 0; $i < strlen ($string); $i++) {
  246. $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
  247. }
  248. return base64_encode($encrypted);
  249. }
  250. /**
  251. * Decrypts a password from the cookie
  252. *
  253. * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
  254. * This uses the encryption key that is stored in the session.
  255. *
  256. * @param string string the string to decrypt
  257. * @param string epad the encryption key from the session
  258. * @return string the decrypted password
  259. */
  260. function OneTimePadDecrypt ($string, $epad) {
  261. $pad = base64_decode($epad);
  262. $encrypted = base64_decode ($string);
  263. $decrypted = '';
  264. for ($i = 0; $i < strlen ($encrypted); $i++) {
  265. $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
  266. }
  267. return $decrypted;
  268. }
  269. /**
  270. * Randomizes the mt_rand() function.
  271. *
  272. * Toss this in strings or integers and it will seed the generator
  273. * appropriately. With strings, it is better to get them long.
  274. * Use md5() to lengthen smaller strings.
  275. *
  276. * @param mixed val a value to seed the random number generator
  277. * @return void
  278. */
  279. function sq_mt_seed($Val) {
  280. /* if mt_getrandmax() does not return a 2^n - 1 number,
  281. this might not work well. This uses $Max as a bitmask. */
  282. $Max = mt_getrandmax();
  283. if (! is_int($Val)) {
  284. $Val = crc32($Val);
  285. }
  286. if ($Val < 0) {
  287. $Val *= -1;
  288. }
  289. if ($Val = 0) {
  290. return;
  291. }
  292. mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
  293. }
  294. /**
  295. * Init random number generator
  296. *
  297. * This function initializes the random number generator fairly well.
  298. * It also only initializes it once, so you don't accidentally get
  299. * the same 'random' numbers twice in one session.
  300. *
  301. * @return void
  302. */
  303. function sq_mt_randomize() {
  304. static $randomized;
  305. if ($randomized) {
  306. return;
  307. }
  308. /* Global. */
  309. sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER);
  310. sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER);
  311. sq_mt_seed((int)((double) microtime() * 1000000));
  312. sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
  313. /* getrusage */
  314. if (function_exists('getrusage')) {
  315. /* Avoid warnings with Win32 */
  316. $dat = @getrusage();
  317. if (isset($dat) && is_array($dat)) {
  318. $Str = '';
  319. foreach ($dat as $k => $v)
  320. {
  321. $Str .= $k . $v;
  322. }
  323. sq_mt_seed(md5($Str));
  324. }
  325. }
  326. if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER)) {
  327. sq_mt_seed(md5($unique_id));
  328. }
  329. $randomized = 1;
  330. }
  331. /**
  332. * Creates encryption key
  333. *
  334. * Creates an encryption key for encrypting the password stored in the cookie.
  335. * The encryption key itself is stored in the session.
  336. *
  337. * @param int length optional, length of the string to generate
  338. * @return string the encryption key
  339. */
  340. function OneTimePadCreate ($length=100) {
  341. sq_mt_randomize();
  342. $pad = '';
  343. for ($i = 0; $i < $length; $i++) {
  344. $pad .= chr(mt_rand(0,255));
  345. }
  346. return base64_encode($pad);
  347. }
  348. /**
  349. * Returns a string showing the size of the message/attachment.
  350. *
  351. * @param int bytes the filesize in bytes
  352. * @return string the filesize in human readable format
  353. */
  354. function show_readable_size($bytes) {
  355. $bytes /= 1024;
  356. $type = 'k';
  357. if ($bytes / 1024 > 1) {
  358. $bytes /= 1024;
  359. $type = 'M';
  360. }
  361. if ($bytes < 10) {
  362. $bytes *= 10;
  363. settype($bytes, 'integer');
  364. $bytes /= 10;
  365. } else {
  366. settype($bytes, 'integer');
  367. }
  368. return $bytes . '<small>&nbsp;' . $type . '</small>';
  369. }
  370. /**
  371. * Generates a random string from the caracter set you pass in
  372. *
  373. * @param int size the size of the string to generate
  374. * @param string chars a string containing the characters to use
  375. * @param int flags a flag to add a specific set to the characters to use:
  376. * Flags:
  377. * 1 = add lowercase a-z to $chars
  378. * 2 = add uppercase A-Z to $chars
  379. * 4 = add numbers 0-9 to $chars
  380. * @return string the random string
  381. */
  382. function GenerateRandomString($size, $chars, $flags = 0) {
  383. if ($flags & 0x1) {
  384. $chars .= 'abcdefghijklmnopqrstuvwxyz';
  385. }
  386. if ($flags & 0x2) {
  387. $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  388. }
  389. if ($flags & 0x4) {
  390. $chars .= '0123456789';
  391. }
  392. if (($size < 1) || (strlen($chars) < 1)) {
  393. return '';
  394. }
  395. sq_mt_randomize(); /* Initialize the random number generator */
  396. $String = '';
  397. $j = strlen( $chars ) - 1;
  398. while (strlen($String) < $size) {
  399. $String .= $chars{mt_rand(0, $j)};
  400. }
  401. return $String;
  402. }
  403. /**
  404. * Escapes special characters for use in IMAP commands.
  405. *
  406. * @param string the string to escape
  407. * @return string the escaped string
  408. */
  409. function quoteimap($str) {
  410. return preg_replace("/([\"\\\\])/", "\\\\$1", $str);
  411. }
  412. /**
  413. * Trims array
  414. *
  415. * Trims every element in the array, ie. remove the first char of each element
  416. * @param array array the array to trim
  417. */
  418. function TrimArray(&$array) {
  419. foreach ($array as $k => $v) {
  420. global $$k;
  421. if (is_array($$k)) {
  422. foreach ($$k as $k2 => $v2) {
  423. $$k[$k2] = substr($v2, 1);
  424. }
  425. } else {
  426. $$k = substr($v, 1);
  427. }
  428. /* Re-assign back to array. */
  429. $array[$k] = $$k;
  430. }
  431. }
  432. /**
  433. * Create compose link
  434. *
  435. * Returns a link to the compose-page, taking in consideration
  436. * the compose_in_new and javascript settings.
  437. * @param string url the URL to the compose page
  438. * @param string text the link text, default "Compose"
  439. * @return string a link to the compose page
  440. */
  441. function makeComposeLink($url, $text = null, $target='')
  442. {
  443. global $compose_new_win,$javascript_on;
  444. if(!$text) {
  445. $text = _("Compose");
  446. }
  447. // if not using "compose in new window", make
  448. // regular link and be done with it
  449. if($compose_new_win != '1') {
  450. return makeInternalLink($url, $text, $target);
  451. }
  452. // build the compose in new window link...
  453. // if javascript is on, use onClick event to handle it
  454. if($javascript_on) {
  455. sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION);
  456. return '<a href="javascript:void(0)" onclick="comp_in_new(\''.$base_uri.$url.'\')">'. $text.'</a>';
  457. }
  458. // otherwise, just open new window using regular HTML
  459. return makeInternalLink($url, $text, '_blank');
  460. }
  461. /**
  462. * Print variable
  463. *
  464. * sm_print_r($some_variable, [$some_other_variable [, ...]]);
  465. *
  466. * Debugging function - does the same as print_r, but makes sure special
  467. * characters are converted to htmlentities first. This will allow
  468. * values like <some@email.address> to be displayed.
  469. * The output is wrapped in <<pre>> and <</pre>> tags.
  470. *
  471. * @return void
  472. */
  473. function sm_print_r() {
  474. ob_start(); // Buffer output
  475. foreach(func_get_args() as $var) {
  476. print_r($var);
  477. echo "\n";
  478. }
  479. $buffer = ob_get_contents(); // Grab the print_r output
  480. ob_end_clean(); // Silently discard the output & stop buffering
  481. print '<pre>';
  482. print htmlentities($buffer);
  483. print '</pre>';
  484. }
  485. /**
  486. * version of fwrite which checks for failure
  487. */
  488. function sq_fwrite($fp, $string) {
  489. // write to file
  490. $count = @fwrite($fp,$string);
  491. // the number of bytes written should be the length of the string
  492. if($count != strlen($string)) {
  493. return FALSE;
  494. }
  495. return $count;
  496. }
  497. /**
  498. * sq_get_html_translation_table
  499. *
  500. * Returns the translation table used by sq_htmlentities()
  501. *
  502. * @param integer $table html translation table. Possible values (without quotes):
  503. * <ul>
  504. * <li>HTML_ENTITIES - full html entities table defined by charset</li>
  505. * <li>HTML_SPECIALCHARS - html special characters table</li>
  506. * </ul>
  507. * @param integer $quote_style quote encoding style. Possible values (without quotes):
  508. * <ul>
  509. * <li>ENT_COMPAT - (default) encode double quotes</li>
  510. * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
  511. * <li>ENT_QUOTES - encode double and single quotes</li>
  512. * </ul>
  513. * @param string $charset charset used for encoding. default to us-ascii, 'auto' uses $default_charset global value.
  514. * @return array html translation array
  515. */
  516. function sq_get_html_translation_table($table,$quote_style=ENT_COMPAT,$charset='us-ascii') {
  517. global $default_charset;
  518. if ($table == HTML_SPECIALCHARS) $charset='us-ascii';
  519. // Start array with ampersand
  520. $sq_html_ent_table = array( "&" => '&amp;' );
  521. // < and >
  522. $sq_html_ent_table = array_merge($sq_html_ent_table,
  523. array("<" => '&lt;',
  524. ">" => '&gt;')
  525. );
  526. // double quotes
  527. if ($quote_style == ENT_COMPAT)
  528. $sq_html_ent_table = array_merge($sq_html_ent_table,
  529. array("\"" => '&quot;')
  530. );
  531. // double and single quotes
  532. if ($quote_style == ENT_QUOTES)
  533. $sq_html_ent_table = array_merge($sq_html_ent_table,
  534. array("\"" => '&quot;',
  535. "'" => '&#39;')
  536. );
  537. if ($charset=='auto') $charset=$default_charset;
  538. // add entities that depend on charset
  539. switch($charset){
  540. case 'iso-8859-1':
  541. include_once(SM_PATH . 'functions/htmlentities/iso-8859-1.php');
  542. break;
  543. case 'utf-8':
  544. include_once(SM_PATH . 'functions/htmlentities/utf-8.php');
  545. break;
  546. case 'us-ascii':
  547. default:
  548. break;
  549. }
  550. // return table
  551. return $sq_html_ent_table;
  552. }
  553. /**
  554. * sq_htmlentities
  555. *
  556. * Convert all applicable characters to HTML entities.
  557. * Minimal php requirement - v.4.0.5
  558. *
  559. * @param string $string string that has to be sanitized
  560. * @param integer $quote_style quote encoding style. Possible values (without quotes):
  561. * <ul>
  562. * <li>ENT_COMPAT - (default) encode double quotes</li>
  563. * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
  564. * <li>ENT_QUOTES - encode double and single quotes</li>
  565. * </ul>
  566. * @param string $charset charset used for encoding. defaults to 'us-ascii', 'auto' uses $default_charset global value.
  567. * @return string sanitized string
  568. */
  569. function sq_htmlentities($string,$quote_style=ENT_COMPAT,$charset='us-ascii') {
  570. // get translation table
  571. $sq_html_ent_table=sq_get_html_translation_table(HTML_ENTITIES,$quote_style,$charset);
  572. // convert characters
  573. return str_replace(array_keys($sq_html_ent_table),array_values($sq_html_ent_table),$string);
  574. }
  575. $PHP_SELF = php_self();
  576. ?>