strings.php 16 KB

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