strings.php 17 KB

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