strings.php 16 KB

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