strings.php 16 KB

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