strings.php 14 KB

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