strings.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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. * $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. * Creates an URL for the page calling this function, using either the PHP global
  146. * REQUEST_URI, or the PHP global PHP_SELF with QUERY_STRING added.
  147. *
  148. * @return string the complete url for this page
  149. */
  150. function php_self () {
  151. if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER) && !empty($req_uri) ) {
  152. return $req_uri;
  153. }
  154. if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER) && !empty($php_self) ) {
  155. // need to add query string to end of PHP_SELF to match REQUEST_URI
  156. //
  157. if ( sqgetGlobalVar('QUERY_STRING', $query_string, SQ_SERVER) && !empty($query_string) ) {
  158. $php_self .= '?' . $query_string;
  159. }
  160. return $php_self;
  161. }
  162. return '';
  163. }
  164. /**
  165. * Determines the location to forward to, relative to your server.
  166. * This is used in HTTP Location: redirects.
  167. * If this doesnt work correctly for you (although it should), you can
  168. * remove all this code except the last two lines, and have it return
  169. * the right URL for your site, something like:
  170. *
  171. * http://www.example.com/squirrelmail/
  172. *
  173. * @return string the base url for this SquirrelMail installation
  174. */
  175. function get_location () {
  176. global $imap_server_type;
  177. /* Get the path, handle virtual directories */
  178. if(strpos(php_self(), '?')) {
  179. $path = substr(php_self(), 0, strpos(php_self(), '?'));
  180. } else {
  181. $path = php_self();
  182. }
  183. $path = substr($path, 0, strrpos($path, '/'));
  184. if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
  185. return $full_url . $path;
  186. }
  187. /* Check if this is a HTTPS or regular HTTP request. */
  188. $proto = 'http://';
  189. /*
  190. * If you have 'SSLOptions +StdEnvVars' in your apache config
  191. * OR if you have HTTPS=on in your HTTP_SERVER_VARS
  192. * OR if you are on port 443
  193. */
  194. $getEnvVar = getenv('HTTPS');
  195. if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
  196. (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER) && !strcasecmp($https_on, 'on')) ||
  197. (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER) && $server_port == 443)) {
  198. $proto = 'https://';
  199. }
  200. /* Get the hostname from the Host header or server config. */
  201. if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
  202. if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
  203. $host = '';
  204. }
  205. }
  206. $port = '';
  207. if (! strstr($host, ':')) {
  208. if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
  209. if (($server_port != 80 && $proto == 'http://') ||
  210. ($server_port != 443 && $proto == 'https://')) {
  211. $port = sprintf(':%d', $server_port);
  212. }
  213. }
  214. }
  215. /* this is a workaround for the weird macosx caching that
  216. causes Apache to return 16080 as the port number, which causes
  217. SM to bail */
  218. if ($imap_server_type == 'macosx' && $port == ':16080') {
  219. $port = '';
  220. }
  221. /* Fallback is to omit the server name and use a relative */
  222. /* URI, although this is not RFC 2616 compliant. */
  223. $full_url = ($host ? $proto . $host . $port : '');
  224. sqsession_register($full_url, 'sq_base_url');
  225. return $full_url . $path;
  226. }
  227. /**
  228. * These functions are used to encrypt the password before it is
  229. * stored in a cookie. The encryption key is generated by
  230. * OneTimePadCreate();
  231. *
  232. * @param string string the (password)string to encrypt
  233. * @param string epad the encryption key
  234. * @return string the base64-encoded encrypted password
  235. */
  236. function OneTimePadEncrypt ($string, $epad) {
  237. $pad = base64_decode($epad);
  238. $encrypted = '';
  239. for ($i = 0; $i < strlen ($string); $i++) {
  240. $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
  241. }
  242. return base64_encode($encrypted);
  243. }
  244. /**
  245. * Decrypt a password from the cookie, encrypted by OneTimePadEncrypt.
  246. * This uses the encryption key that is stored in the session.
  247. *
  248. * @param string string the string to decrypt
  249. * @param string epad the encryption key from the session
  250. * @return string the decrypted password
  251. */
  252. function OneTimePadDecrypt ($string, $epad) {
  253. $pad = base64_decode($epad);
  254. $encrypted = base64_decode ($string);
  255. $decrypted = '';
  256. for ($i = 0; $i < strlen ($encrypted); $i++) {
  257. $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
  258. }
  259. return $decrypted;
  260. }
  261. /**
  262. * Randomize the mt_rand() function. Toss this in strings or integers
  263. * and it will seed the generator appropriately. With strings, it is
  264. * better to get them long. Use md5() to lengthen smaller strings.
  265. *
  266. * @param mixed val a value to seed the random number generator
  267. * @return void
  268. */
  269. function sq_mt_seed($Val) {
  270. /* if mt_getrandmax() does not return a 2^n - 1 number,
  271. this might not work well. This uses $Max as a bitmask. */
  272. $Max = mt_getrandmax();
  273. if (! is_int($Val)) {
  274. $Val = crc32($Val);
  275. }
  276. if ($Val < 0) {
  277. $Val *= -1;
  278. }
  279. if ($Val = 0) {
  280. return;
  281. }
  282. mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
  283. }
  284. /**
  285. * This function initializes the random number generator fairly well.
  286. * It also only initializes it once, so you don't accidentally get
  287. * the same 'random' numbers twice in one session.
  288. *
  289. * @return void
  290. */
  291. function sq_mt_randomize() {
  292. static $randomized;
  293. if ($randomized) {
  294. return;
  295. }
  296. /* Global. */
  297. sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER);
  298. sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER);
  299. sq_mt_seed((int)((double) microtime() * 1000000));
  300. sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
  301. /* getrusage */
  302. if (function_exists('getrusage')) {
  303. /* Avoid warnings with Win32 */
  304. $dat = @getrusage();
  305. if (isset($dat) && is_array($dat)) {
  306. $Str = '';
  307. foreach ($dat as $k => $v)
  308. {
  309. $Str .= $k . $v;
  310. }
  311. sq_mt_seed(md5($Str));
  312. }
  313. }
  314. if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER)) {
  315. sq_mt_seed(md5($unique_id));
  316. }
  317. $randomized = 1;
  318. }
  319. /**
  320. * Creates an encryption key for encrypting the password stored in the cookie.
  321. * The encryption key itself is stored in the session.
  322. *
  323. * @param int length optional, length of the string to generate
  324. * @return string the encryption key
  325. */
  326. function OneTimePadCreate ($length=100) {
  327. sq_mt_randomize();
  328. $pad = '';
  329. for ($i = 0; $i < $length; $i++) {
  330. $pad .= chr(mt_rand(0,255));
  331. }
  332. return base64_encode($pad);
  333. }
  334. /**
  335. * Returns a string showing the size of the message/attachment.
  336. *
  337. * @param int bytes the filesize in bytes
  338. * @return string the filesize in human readable format
  339. */
  340. function show_readable_size($bytes) {
  341. $bytes /= 1024;
  342. $type = 'k';
  343. if ($bytes / 1024 > 1) {
  344. $bytes /= 1024;
  345. $type = 'M';
  346. }
  347. if ($bytes < 10) {
  348. $bytes *= 10;
  349. settype($bytes, 'integer');
  350. $bytes /= 10;
  351. } else {
  352. settype($bytes, 'integer');
  353. }
  354. return $bytes . '<small>&nbsp;' . $type . '</small>';
  355. }
  356. /**
  357. * Generates a random string from the caracter set you pass in
  358. *
  359. * @param int size the size of the string to generate
  360. * @param string chars a string containing the characters to use
  361. * @param int flags a flag to add a specific set to the characters to use:
  362. * Flags:
  363. * 1 = add lowercase a-z to $chars
  364. * 2 = add uppercase A-Z to $chars
  365. * 4 = add numbers 0-9 to $chars
  366. * @return string the random string
  367. */
  368. function GenerateRandomString($size, $chars, $flags = 0) {
  369. if ($flags & 0x1) {
  370. $chars .= 'abcdefghijklmnopqrstuvwxyz';
  371. }
  372. if ($flags & 0x2) {
  373. $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  374. }
  375. if ($flags & 0x4) {
  376. $chars .= '0123456789';
  377. }
  378. if (($size < 1) || (strlen($chars) < 1)) {
  379. return '';
  380. }
  381. sq_mt_randomize(); /* Initialize the random number generator */
  382. $String = '';
  383. $j = strlen( $chars ) - 1;
  384. while (strlen($String) < $size) {
  385. $String .= $chars{mt_rand(0, $j)};
  386. }
  387. return $String;
  388. }
  389. /**
  390. * Escapes special characters for use in IMAP commands.
  391. * @param string the string to escape
  392. * @return string the escaped string
  393. */
  394. function quoteimap($str) {
  395. return preg_replace("/([\"\\\\])/", "\\\\$1", $str);
  396. }
  397. /**
  398. * Trims every element in the array, ie. remove the first char of each element
  399. * @param array array the array to trim
  400. */
  401. function TrimArray(&$array) {
  402. foreach ($array as $k => $v) {
  403. global $$k;
  404. if (is_array($$k)) {
  405. foreach ($$k as $k2 => $v2) {
  406. $$k[$k2] = substr($v2, 1);
  407. }
  408. } else {
  409. $$k = substr($v, 1);
  410. }
  411. /* Re-assign back to array. */
  412. $array[$k] = $$k;
  413. }
  414. }
  415. /**
  416. * Returns a link to the compose-page, taking in consideration
  417. * the compose_in_new and javascript settings.
  418. * @param string url the URL to the compose page
  419. * @param string text the link text, default "Compose"
  420. * @return string a link to the compose page
  421. */
  422. function makeComposeLink($url, $text = null, $target='')
  423. {
  424. global $compose_new_win,$javascript_on;
  425. if(!$text) {
  426. $text = _("Compose");
  427. }
  428. // if not using "compose in new window", make
  429. // regular link and be done with it
  430. if($compose_new_win != '1') {
  431. return makeInternalLink($url, $text, $target);
  432. }
  433. // build the compose in new window link...
  434. // if javascript is on, use onClick event to handle it
  435. if($javascript_on) {
  436. sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION);
  437. return '<a href="javascript:void(0)" onclick="comp_in_new(\''.$base_uri.$url.'\')">'. $text.'</a>';
  438. }
  439. // otherwise, just open new window using regular HTML
  440. return makeInternalLink($url, $text, '_blank');
  441. }
  442. /**
  443. * sm_print_r($some_variable, [$some_other_variable [, ...]]);
  444. * Debugging function - does the same as print_r, but makes sure special
  445. * characters are converted to htmlentities first. This will allow
  446. * values like <some@email.address> to be displayed.
  447. * The output is wrapped in <pre> and </pre> tags.
  448. *
  449. * @return void
  450. */
  451. function sm_print_r() {
  452. ob_start(); // Buffer output
  453. foreach(func_get_args() as $var) {
  454. print_r($var);
  455. echo "\n";
  456. }
  457. $buffer = ob_get_contents(); // Grab the print_r output
  458. ob_end_clean(); // Silently discard the output & stop buffering
  459. print '<pre>';
  460. print htmlentities($buffer);
  461. print '</pre>';
  462. }
  463. /**
  464. * version of fwrite which checks for failure
  465. */
  466. function sq_fwrite($fp, $string) {
  467. // write to file
  468. $count = @fwrite($fp,$string);
  469. // the number of bytes written should be the length of the string
  470. if($count != strlen($string)) {
  471. return FALSE;
  472. }
  473. return $count;
  474. }
  475. $PHP_SELF = php_self();
  476. ?>