strings.php 16 KB

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