strings.php 16 KB

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