strings.php 16 KB

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