strings.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. <?php
  2. /**
  3. * strings.php
  4. *
  5. * Copyright (c) 1999-2002 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. */
  13. /*****************************************************************/
  14. /*** THIS FILE NEEDS TO HAVE ITS FORMATTING FIXED!!! ***/
  15. /*** PLEASE DO SO AND REMOVE THIS COMMENT SECTION. ***/
  16. /*** + Base level indent should begin at left margin, as ***/
  17. /*** the comment and $version stuff below. ***/
  18. /*** + All identation should consist of four space blocks ***/
  19. /*** + Tab characters are evil. ***/
  20. /*** + all comments should use "slash-star ... star-slash" ***/
  21. /*** style -- no pound characters, no slash-slash style ***/
  22. /*** + FLOW CONTROL STATEMENTS (if, while, etc) SHOULD ***/
  23. /*** ALWAYS USE { AND } CHARACTERS!!! ***/
  24. /*** + Please use ' instead of ", when possible. Note " ***/
  25. /*** should always be used in _( ) function calls. ***/
  26. /*** Thank you for your help making the SM code more readable. ***/
  27. /*****************************************************************/
  28. /**
  29. * SquirrelMail version number -- DO NOT CHANGE
  30. */
  31. global $version;
  32. $version = '1.2.2';
  33. /**
  34. * If $haystack is a full mailbox name and $needle is the mailbox
  35. * separator character, returns the last part of the mailbox name.
  36. */
  37. function readShortMailboxName($haystack, $needle) {
  38. if ($needle == '') {
  39. return $haystack;
  40. }
  41. $parts = explode($needle, $haystack);
  42. $elem = array_pop($parts);
  43. while ($elem == '' && count($parts)) {
  44. $elem = array_pop($parts);
  45. }
  46. return $elem;
  47. }
  48. /**
  49. * If $haystack is a full mailbox name, and $needle is the mailbox
  50. * separator character, returns the second last part of the full
  51. * mailbox name (i.e. the mailbox's parent mailbox)
  52. */
  53. function readMailboxParent($haystack, $needle) {
  54. if ($needle == '') return '';
  55. $parts = explode($needle, $haystack);
  56. $elem = array_pop($parts);
  57. while ($elem == '' && count($parts)) {
  58. $elem = array_pop($parts);
  59. }
  60. return join($needle, $parts);
  61. }
  62. /**
  63. * Returns the index of the first chunk of string $haystack that
  64. * starts with non-white-space character, starting at position $pos.
  65. * If there is no such chunk, returns -1.
  66. */
  67. function next_pos_minus_white ($haystack, $pos) {
  68. $len = strlen($haystack);
  69. while ($pos < $len) {
  70. /* Get the next character. */
  71. $c = substr($haystack, $pos, 1);
  72. /* Check the next character. */
  73. if (($c != ' ') && ($c != "\t") && ($c != "\n") && ($c != "\r")) {
  74. return $pos;
  75. }
  76. /* Increment position in string. */
  77. ++$pos;
  78. }
  79. return -1;
  80. }
  81. /**
  82. * Wraps text at $wrap characters
  83. *
  84. * Has a problem with special HTML characters, so call this before
  85. * you do character translation.
  86. *
  87. * Specifically, &#039 comes up as 5 characters instead of 1.
  88. * This should not add newlines to the end of lines.
  89. */
  90. function sqWordWrap(&$line, $wrap) {
  91. ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
  92. $beginning_spaces = $regs[1];
  93. if (isset($regs[2])) {
  94. $words = explode(' ', $regs[2]);
  95. } else {
  96. $words = "";
  97. }
  98. $i = 0;
  99. $line = $beginning_spaces;
  100. while ($i < count($words)) {
  101. // Force one word to be on a line (minimum)
  102. $line .= $words[$i];
  103. $line_len = strlen($beginning_spaces) + strlen($words[$i]) + 2;
  104. if (isset($words[$i + 1]))
  105. $line_len += strlen($words[$i + 1]);
  106. $i ++;
  107. // Add more words (as long as they fit)
  108. while ($line_len < $wrap && $i < count($words)) {
  109. $line .= ' ' . $words[$i];
  110. $i++;
  111. if (isset($words[$i]))
  112. $line_len += strlen($words[$i]) + 1;
  113. else
  114. $line_len += 1;
  115. }
  116. // Skip spaces if they are the first thing on a continued line
  117. while (!isset($words[$i]) && $i < count($words)) {
  118. $i ++;
  119. }
  120. // Go to the next line if we have more to process
  121. if ($i < count($words)) {
  122. $line .= "\n" . $beginning_spaces;
  123. }
  124. }
  125. }
  126. /**
  127. * Does the opposite of sqWordWrap()
  128. */
  129. function sqUnWordWrap(&$body) {
  130. $lines = explode("\n", $body);
  131. $body = "";
  132. $PreviousSpaces = "";
  133. for ($i = 0; $i < count($lines); $i ++) {
  134. ereg("^([\t >]*)([^\t >].*)?$", $lines[$i], $regs);
  135. $CurrentSpaces = $regs[1];
  136. if (isset($regs[2])) {
  137. $CurrentRest = $regs[2];
  138. }
  139. if ($i == 0) {
  140. $PreviousSpaces = $CurrentSpaces;
  141. $body = $lines[$i];
  142. } else if (($PreviousSpaces == $CurrentSpaces) // Do the beginnings match
  143. && (strlen($lines[$i - 1]) > 65) // Over 65 characters long
  144. && strlen($CurrentRest)) { // and there's a line to continue with
  145. $body .= ' ' . $CurrentRest;
  146. } else {
  147. $body .= "\n" . $lines[$i];
  148. $PreviousSpaces = $CurrentSpaces;
  149. }
  150. }
  151. $body .= "\n";
  152. }
  153. /**
  154. * Returns an array of email addresses.
  155. * Be cautious of "user@host.com"
  156. */
  157. function parseAddrs($text) {
  158. if (trim($text) == "")
  159. return array();
  160. $text = str_replace(' ', '', $text);
  161. $text = ereg_replace('"[^"]*"', '', $text);
  162. $text = ereg_replace('\\([^\\)]*\\)', '', $text);
  163. $text = str_replace(',', ';', $text);
  164. $array = explode(';', $text);
  165. for ($i = 0; $i < count ($array); $i++) {
  166. $array[$i] = eregi_replace ("^.*[<]", '', $array[$i]);
  167. $array[$i] = eregi_replace ("[>].*$", '', $array[$i]);
  168. }
  169. return $array;
  170. }
  171. /**
  172. * Returns a line of comma separated email addresses from an array.
  173. */
  174. function getLineOfAddrs($array) {
  175. if (is_array($array)) {
  176. $to_line = implode(', ', $array);
  177. $to_line = ereg_replace(', (, )+', ', ', $to_line);
  178. $to_line = trim(ereg_replace('^, ', '', $to_line));
  179. if( substr( $to_line, -1 ) == ',' )
  180. $to_line = substr( $to_line, 0, -1 );
  181. } else {
  182. $to_line = '';
  183. }
  184. return( $to_line );
  185. }
  186. function translateText(&$body, $wrap_at, $charset) {
  187. global $where, $what; // from searching
  188. global $color; // color theme
  189. require_once('../functions/url_parser.php');
  190. $body_ary = explode("\n", $body);
  191. $PriorQuotes = 0;
  192. for ($i=0; $i < count($body_ary); $i++) {
  193. $line = $body_ary[$i];
  194. if (strlen($line) - 2 >= $wrap_at) {
  195. sqWordWrap($line, $wrap_at);
  196. }
  197. $line = charset_decode($charset, $line);
  198. $line = str_replace("\t", ' ', $line);
  199. parseUrl ($line);
  200. $Quotes = 0;
  201. $pos = 0;
  202. while (1) {
  203. if ($line[$pos] == ' ') {
  204. $pos ++;
  205. } else if (strpos($line, '&gt;', $pos) === $pos) {
  206. $pos += 4;
  207. $Quotes ++;
  208. } else {
  209. break;
  210. }
  211. }
  212. if ($Quotes > 1) {
  213. if (! isset($color[14])) {
  214. $color[14] = '#FF0000';
  215. }
  216. $line = '<FONT COLOR="' . $color[14] . '">' . $line . '</FONT>';
  217. } elseif ($Quotes) {
  218. if (! isset($color[13])) {
  219. $color[13] = '#800000';
  220. }
  221. $line = '<FONT COLOR="' . $color[13] . '">' . $line . '</FONT>';
  222. }
  223. $body_ary[$i] = $line;
  224. }
  225. $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
  226. }
  227. function find_mailbox_name ($mailbox) {
  228. if (ereg(" *\"([^\r\n\"]*)\"[ \r\n]*$", $mailbox, $regs))
  229. return $regs[1];
  230. ereg(" *([^ \r\n\"]*)[ \r\n]*$",$mailbox,$regs);
  231. return $regs[1];
  232. }
  233. /**
  234. * This determines the location to forward to relative to your server.
  235. * If this doesnt work correctly for you (although it should), you can
  236. * remove all this code except the last two lines, and change the header()
  237. * function to look something like this, customized to the location of
  238. * SquirrelMail on your server:
  239. *
  240. * http://www.myhost.com/squirrelmail/src/login.php
  241. */
  242. function get_location () {
  243. global $PHP_SELF, $SERVER_NAME, $HTTP_HOST, $SERVER_PORT,
  244. $HTTP_SERVER_VARS;
  245. /* Get the path. */
  246. $path = substr($PHP_SELF, 0, strrpos($PHP_SELF, '/'));
  247. /* Check if this is a HTTPS or regular HTTP request. */
  248. $proto = 'http://';
  249. /*
  250. * If you have 'SSLOptions +StdEnvVars' in your apache config
  251. * OR if you have HTTPS in your HTTP_SERVER_VARS
  252. * OR if you are on port 443
  253. */
  254. $getEnvVar = getenv('HTTPS');
  255. if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
  256. (isset($HTTP_SERVER_VARS['HTTPS'])) ||
  257. (isset($HTTP_SERVER_VARS['SERVER_PORT']) &&
  258. $HTTP_SERVER_VARS['SERVER_PORT'] == 443)) {
  259. $proto = 'https://';
  260. }
  261. // Get the hostname from the Host header or server config.
  262. $host = '';
  263. if (isset($HTTP_HOST) && !empty($HTTP_HOST)) {
  264. $host = $HTTP_HOST;
  265. } else if (isset($SERVER_NAME) && !empty($SERVER_NAME)) {
  266. $host = $SERVER_NAME;
  267. }
  268. $port = '';
  269. if (! strstr($host, ':')) {
  270. if (isset($SERVER_PORT)) {
  271. if (($SERVER_PORT != 80 && $proto == 'http://')
  272. || ($SERVER_PORT != 443 && $proto == 'https://')) {
  273. $port = sprintf(':%d', $SERVER_PORT);
  274. }
  275. }
  276. }
  277. /* Fallback is to omit the server name and use a relative */
  278. /* URI, although this is not RFC 2616 compliant. */
  279. return ($host ? $proto . $host . $port . $path : $path);
  280. }
  281. /**
  282. * These functions are used to encrypt the passowrd before it is
  283. * stored in a cookie.
  284. */
  285. function OneTimePadEncrypt ($string, $epad) {
  286. $pad = base64_decode($epad);
  287. $encrypted = '';
  288. for ($i = 0; $i < strlen ($string); $i++) {
  289. $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
  290. }
  291. return base64_encode($encrypted);
  292. }
  293. function OneTimePadDecrypt ($string, $epad) {
  294. $pad = base64_decode($epad);
  295. $encrypted = base64_decode ($string);
  296. $decrypted = '';
  297. for ($i = 0; $i < strlen ($encrypted); $i++) {
  298. $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
  299. }
  300. return $decrypted;
  301. }
  302. /**
  303. * Randomize the mt_rand() function. Toss this in strings or integers
  304. * and it will seed the generator appropriately. With strings, it is
  305. * better to get them long. Use md5() to lengthen smaller strings.
  306. */
  307. function sq_mt_seed($Val) {
  308. // if mt_getrandmax() does not return a 2^n - 1 number,
  309. // this might not work well. This uses $Max as a bitmask.
  310. $Max = mt_getrandmax();
  311. if (! is_int($Val)) {
  312. if (function_exists('crc32')) {
  313. $Val = crc32($Val);
  314. } else {
  315. $Str = $Val;
  316. $Pos = 0;
  317. $Val = 0;
  318. $Mask = $Max / 2;
  319. $HighBit = $Max ^ $Mask;
  320. while ($Pos < strlen($Str)) {
  321. if ($Val & $HighBit) {
  322. $Val = (($Val & $Mask) << 1) + 1;
  323. } else {
  324. $Val = ($Val & $Mask) << 1;
  325. }
  326. $Val ^= $Str[$Pos];
  327. $Pos ++;
  328. }
  329. }
  330. }
  331. if ($Val < 0) {
  332. $Val *= -1;
  333. }
  334. if ($Val = 0) {
  335. return;
  336. }
  337. mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
  338. }
  339. /**
  340. * This function initializes the random number generator fairly well.
  341. * It also only initializes it once, so you don't accidentally get
  342. * the same 'random' numbers twice in one session.
  343. */
  344. function sq_mt_randomize() {
  345. global $REMOTE_PORT, $REMOTE_ADDR, $UNIQUE_ID;
  346. static $randomized;
  347. if ($randomized) {
  348. return;
  349. }
  350. /* Global. */
  351. sq_mt_seed((int)((double) microtime() * 1000000));
  352. sq_mt_seed(md5($REMOTE_PORT . $REMOTE_ADDR . getmypid()));
  353. /* getrusage */
  354. if (function_exists('getrusage')) {
  355. // Avoid warnings with Win32
  356. $dat = @getrusage();
  357. if (isset($dat) && is_array($dat)) {
  358. $Str = '';
  359. foreach ($dat as $k => $v)
  360. {
  361. $Str .= $k . $v;
  362. }
  363. sq_mt_seed(md5($Str));
  364. }
  365. }
  366. // Apache-specific
  367. sq_mt_seed(md5($UNIQUE_ID));
  368. $randomized = 1;
  369. }
  370. function OneTimePadCreate ($length=100) {
  371. sq_mt_randomize();
  372. $pad = '';
  373. for ($i = 0; $i < $length; $i++) {
  374. $pad .= chr(mt_rand(0,255));
  375. }
  376. return base64_encode($pad);
  377. }
  378. /**
  379. * Check if we have a required PHP-version. Return TRUE if we do,
  380. * or FALSE if we don't.
  381. *
  382. * To check for 4.0.1, use sqCheckPHPVersion(4,0,1)
  383. * To check for 4.0b3, use sqCheckPHPVersion(4,0,-3)
  384. *
  385. * Does not handle betas like 4.0.1b1 or development versions
  386. */
  387. function sqCheckPHPVersion($major, $minor, $release) {
  388. $ver = phpversion();
  389. eregi('^([0-9]+)\\.([0-9]+)(.*)', $ver, $regs);
  390. /* Parse the version string. */
  391. $vmajor = strval($regs[1]);
  392. $vminor = strval($regs[2]);
  393. $vrel = $regs[3];
  394. if($vrel[0] == ".") {
  395. $vrel = strval(substr($vrel, 1));
  396. }
  397. if($vrel[0] == 'b' || $vrel[0] == 'B') {
  398. $vrel = - strval(substr($vrel, 1));
  399. }
  400. if($vrel[0] == 'r' || $vrel[0] == 'R') {
  401. $vrel = - strval(substr($vrel, 2))/10;
  402. }
  403. /* Compare major version. */
  404. if ($vmajor < $major) { return false; }
  405. if ($vmajor > $major) { return true; }
  406. /* Major is the same. Compare minor. */
  407. if ($vminor < $minor) { return false; }
  408. if ($vminor > $minor) { return true; }
  409. /* Major and minor is the same as the required one. Compare release */
  410. if ($vrel >= 0 && $release >= 0) { // Neither are beta
  411. if($vrel < $release) return false;
  412. } else if($vrel >= 0 && $release < 0) { // This is not beta, required is beta
  413. return true;
  414. } else if($vrel < 0 && $release >= 0){ // This is beta, require not beta
  415. return false;
  416. } else { // Both are beta
  417. if($vrel > $release) return false;
  418. }
  419. return true;
  420. }
  421. /**
  422. * Returns a string showing the size of the message/attachment.
  423. */
  424. function show_readable_size($bytes) {
  425. $bytes /= 1024;
  426. $type = 'k';
  427. if ($bytes / 1024 > 1) {
  428. $bytes /= 1024;
  429. $type = 'm';
  430. }
  431. if ($bytes < 10) {
  432. $bytes *= 10;
  433. settype($bytes, 'integer');
  434. $bytes /= 10;
  435. } else {
  436. settype($bytes, 'integer');
  437. }
  438. return $bytes . '<small>&nbsp;' . $type . '</small>';
  439. }
  440. /**
  441. * Generates a random string from the caracter set you pass in
  442. *
  443. * Flags:
  444. * 1 = add lowercase a-z to $chars
  445. * 2 = add uppercase A-Z to $chars
  446. * 4 = add numbers 0-9 to $chars
  447. */
  448. function GenerateRandomString($size, $chars, $flags = 0) {
  449. if ($flags & 0x1) {
  450. $chars .= 'abcdefghijklmnopqrstuvwxyz';
  451. }
  452. if ($flags & 0x2) {
  453. $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  454. }
  455. if ($flags & 0x4) {
  456. $chars .= '0123456789';
  457. }
  458. if (($size < 1) || (strlen($chars) < 1)) {
  459. return '';
  460. }
  461. sq_mt_randomize(); // Initialize the random number generator
  462. $String = "";
  463. while (strlen($String) < $size) {
  464. $String .= $chars[mt_rand(0, strlen($chars))];
  465. }
  466. return $String;
  467. }
  468. function quoteIMAP($str) {
  469. return ereg_replace('(["\\])', '\\\\1', $str);
  470. }
  471. /**
  472. * Trims every element in the array
  473. */
  474. function TrimArray(&$array) {
  475. foreach ($array as $k => $v) {
  476. global $$k;
  477. if (is_array($$k)) {
  478. foreach ($$k as $k2 => $v2) {
  479. $$k[$k2] = substr($v2, 1);
  480. }
  481. } else {
  482. $$k = substr($v, 1);
  483. }
  484. /* Re-assign back to array. */
  485. $array[$k] = $$k;
  486. }
  487. }
  488. /**
  489. * Removes slashes from every element in the array
  490. */
  491. function RemoveSlashes(&$array) {
  492. foreach ($array as $k => $v) {
  493. global $$k;
  494. if (is_array($$k)) {
  495. foreach ($$k as $k2 => $v2) {
  496. $newArray[stripslashes($k2)] = stripslashes($v2);
  497. }
  498. $$k = $newArray;
  499. } else {
  500. $$k = stripslashes($v);
  501. }
  502. /* Re-assign back to the array. */
  503. $array[$k] = $$k;
  504. }
  505. }
  506. ?>