strings.php 13 KB

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