Some user interface changes.
[squirrelmail.git] / functions / strings.php
CommitLineData
59177427 1<?php
23d6bd09 2 /**
3 * strings.php
4 * Copyright (c) 1999-2001 The Squirrelmail Development Team
5 * Licensed under the GNU GPL. For full terms see the file COPYING.
6 *
7 * This code provides various string manipulation functions that are
8 * used by the rest of the Squirrelmail code.
9 *
10 * $Id$
11 */
9374671f 12
23d6bd09 13 if (defined('strings_php')) { return; }
14 define('strings_php', true);
d51894be 15
23d6bd09 16 /**
17 * SquirrelMail version number -- DO NOT CHANGE
18 */
19 global $version;
20 $version = '1.2.0 [cvs]';
d068c0ec 21
23d6bd09 22 /**
23 * Count the number of occurances of $needle are in $haystack.
24 * $needle can be a character or string, and need not occur in $haystack
25 */
3302d0d4 26 function countCharInString($haystack, $needle) {
37a17ace 27 if ($needle == '') return 0;
28 return count(explode($needle, $haystack));
3302d0d4 29 }
30
23d6bd09 31 /**
32 * Read from the back of $haystack until $needle is found, or the begining
33 * of the $haystack is reached. $needle is a single character
34 */
3302d0d4 35 function readShortMailboxName($haystack, $needle) {
8a549df2 36 if ($needle == '') return $haystack;
37a17ace 37 $parts = explode($needle, $haystack);
38 $elem = array_pop($parts);
39 while ($elem == '' && count($parts))
40 {
41 $elem = array_pop($parts);
42 }
43 return $elem;
3302d0d4 44 }
45
23d6bd09 46 /**
47 * Read from the back of $haystack until $needle is found, or the begining
48 * of the $haystack is reached. $needle is a single character
49 */
5bdd7223 50 function readMailboxParent($haystack, $needle) {
37a17ace 51 if ($needle == '') return '';
52 $parts = explode($needle, $haystack);
53 $elem = array_pop($parts);
54 while ($elem == '' && count($parts))
55 {
56 $elem = array_pop($parts);
57 }
58 return join($needle, $parts);
5bdd7223 59 }
60
23d6bd09 61 /**
62 * Searches for the next position in a string minus white space.
63 */
8beafbbc 64 function next_pos_minus_white ($haystack, $pos) {
8a549df2 65 while (substr($haystack, $pos, 1) == ' ' ||
8beafbbc 66 substr($haystack, $pos, 1) == "\t" ||
67 substr($haystack, $pos, 1) == "\n" ||
68 substr($haystack, $pos, 1) == "\r") {
69 if ($pos >= strlen($haystack))
70 return -1;
71 $pos++;
9374671f 72 }
73 return $pos;
8beafbbc 74 }
75
23d6bd09 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 */
9eea179c 85 function sqWordWrap(&$line, $wrap) {
146e0c45 86 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
45f6dd68 87 $beginning_spaces = $regs[1];
65f5b1c4 88 if (isset($regs[2])) {
23fd3c8e 89 $words = explode(' ', $regs[2]);
90 } else {
91 $words = "";
65f5b1c4 92 }
a95681a7 93
94 $i = 0;
95 $line = $beginning_spaces;
9374671f 96
bcad90fe 97 while ($i < count($words)) {
98 // Force one word to be on a line (minimum)
99 $line .= $words[$i];
48f8ce2f 100 $line_len = strlen($beginning_spaces) + strlen($words[$i]) + 2;
65f5b1c4 101 if (isset($words[$i + 1]))
102 $line_len += strlen($words[$i + 1]);
bcad90fe 103 $i ++;
9374671f 104
bcad90fe 105 // Add more words (as long as they fit)
106 while ($line_len < $wrap && $i < count($words)) {
107 $line .= ' ' . $words[$i];
108 $i++;
65f5b1c4 109 if (isset($words[$i]))
48f8ce2f 110 $line_len += strlen($words[$i]) + 1;
65f5b1c4 111 else
112 $line_len += 1;
bcad90fe 113 }
9374671f 114
bcad90fe 115 // Skip spaces if they are the first thing on a continued line
48f8ce2f 116 while (!isset($words[$i]) && $i < count($words)) {
bcad90fe 117 $i ++;
118 }
8ceb637a 119
9374671f 120 // Go to the next line if we have more to process
bcad90fe 121 if ($i < count($words)) {
5be8bbd8 122 $line .= "\n" . $beginning_spaces;
b8ea4ed6 123 }
e550d551 124 }
e550d551 125 }
9374671f 126
127
23d6bd09 128 /**
129 * Does the opposite of sqWordWrap()
130 */
131 function sqUnWordWrap(&$body) {
01aab860 132 $lines = explode("\n", $body);
133 $body = "";
134 $PreviousSpaces = "";
23d6bd09 135 for ($i = 0; $i < count($lines); $i ++) {
146e0c45 136 ereg("^([\t >]*)([^\t >].*)?$", $lines[$i], $regs);
01aab860 137 $CurrentSpaces = $regs[1];
23d6bd09 138 if (isset($regs[2])) {
48f8ce2f 139 $CurrentRest = $regs[2];
23d6bd09 140 }
141
142 if ($i == 0) {
01aab860 143 $PreviousSpaces = $CurrentSpaces;
144 $body = $lines[$i];
23d6bd09 145 } else if (($PreviousSpaces == $CurrentSpaces) // Do the beginnings match
146 && (strlen($lines[$i - 1]) > 65) // Over 65 characters long
147 && strlen($CurrentRest)) { // and there's a line to continue with
01aab860 148 $body .= ' ' . $CurrentRest;
23d6bd09 149 } else {
01aab860 150 $body .= "\n" . $lines[$i];
151 $PreviousSpaces = $CurrentSpaces;
152 }
153 }
154 $body .= "\n";
155 }
9374671f 156
40ee9452 157
23d6bd09 158 /**
159 * Returns an array of email addresses.
160 * Be cautious of "user@host.com"
161 */
40ee9452 162 function parseAddrs($text) {
1d2ce1c3 163 if (trim($text) == "")
c5edd369 164 return array();
8a549df2 165 $text = str_replace(' ', '', $text);
166 $text = ereg_replace('"[^"]*"', '', $text);
5be8bbd8 167 $text = ereg_replace('\\([^\\)]*\\)', '', $text);
8a549df2 168 $text = str_replace(',', ';', $text);
169 $array = explode(';', $text);
1d2ce1c3 170 for ($i = 0; $i < count ($array); $i++) {
65f5b1c4 171 $array[$i] = eregi_replace ("^.*[<]", '', $array[$i]);
172 $array[$i] = eregi_replace ("[>].*$", '', $array[$i]);
173 }
1d2ce1c3 174 return $array;
40ee9452 175 }
176
23d6bd09 177 /**
178 * Returns a line of comma separated email addresses from an array.
179 */
40ee9452 180 function getLineOfAddrs($array) {
b676ba7e 181 if (is_array($array)) {
8a549df2 182 $to_line = implode(', ', $array);
d46b103b 183 $to_line = ereg_replace(', (, )+', ', ', $to_line);
184 $to_line = trim(ereg_replace('^, ', '', $to_line));
185 if( substr( $to_line, -1 ) == ',' )
186 $to_line = substr( $to_line, 0, -1 );
b676ba7e 187 } else {
8a549df2 188 $to_line = '';
40ee9452 189 }
9374671f 190
9374671f 191 return( $to_line );
40ee9452 192 }
7ce342dc 193
9eea179c 194 function translateText(&$body, $wrap_at, $charset) {
9297917e 195 global $where, $what; // from searching
0391864c 196 global $color; // color theme
9297917e 197
0fc2aca0 198 require_once('../functions/url_parser.php');
9374671f 199
a8648d75 200 $body_ary = explode("\n", $body);
8ceb637a 201 $PriorQuotes = 0;
8442ac08 202 for ($i=0; $i < count($body_ary); $i++) {
a8648d75 203 $line = $body_ary[$i];
a37f3771 204 if (strlen($line) - 2 >= $wrap_at) {
9374671f 205 sqWordWrap($line, $wrap_at);
a37f3771 206 }
a95681a7 207 $line = charset_decode($charset, $line);
208 $line = str_replace("\t", ' ', $line);
9374671f 209
9eea179c 210 parseUrl ($line);
9374671f 211
9eea179c 212 $Quotes = 0;
213 $pos = 0;
23d6bd09 214 while (1) {
215 if ($line[$pos] == ' ') {
8ceb637a 216 $pos ++;
23d6bd09 217 } else if (strpos($line, '&gt;', $pos) === $pos) {
9eea179c 218 $pos += 4;
219 $Quotes ++;
23d6bd09 220 } else {
9eea179c 221 break;
222 }
223 }
9374671f 224
0391864c 225 if ($Quotes > 1) {
23d6bd09 226 if (! isset($color[14])) {
24194051 227 $color[14] = '#FF0000';
23d6bd09 228 }
0391864c 229 $line = '<FONT COLOR="' . $color[14] . '">' . $line . '</FONT>';
24194051 230 } elseif ($Quotes) {
23d6bd09 231 if (! isset($color[13])) {
24194051 232 $color[13] = '#800000';
23d6bd09 233 }
24194051 234 $line = '<FONT COLOR="' . $color[13] . '">' . $line . '</FONT>';
0391864c 235 }
e2ef6f4b 236
8ceb637a 237 $body_ary[$i] = $line;
a8648d75 238 }
8a549df2 239 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
78509c54 240 }
241
d29aac0e 242 function find_mailbox_name ($mailbox) {
f9b3e5d9 243 if (ereg(" *\"([^\r\n\"]*)\"[ \r\n]*$", $mailbox, $regs))
244 return $regs[1];
245 ereg(" *([^ \r\n\"]*)[ \r\n]*$",$mailbox,$regs);
246 return $regs[1];
247
d29aac0e 248 }
249
23d6bd09 250 /**
251 * This determines the location to forward to relative to your server.
252 * If this doesnt work correctly for you (although it should), you can
253 * remove all this code except the last two lines, and change the header()
254 * function to look something like this, customized to the location of
255 * SquirrelMail on your server:
256 *
257 * http://www.myhost.com/squirrelmail/src/login.php
258 */
1195c340 259 function get_location () {
9374671f 260
c731b9f7 261 global $PHP_SELF, $SERVER_NAME, $HTTP_HOST, $SERVER_PORT,
262 $HTTP_SERVER_VARS;
841291c2 263
23d6bd09 264 /* Get the path. */
1195c340 265 $path = substr($PHP_SELF, 0, strrpos($PHP_SELF, '/'));
9374671f 266
23d6bd09 267 /* Check if this is a HTTPS or regular HTTP request. */
8a549df2 268 $proto = 'http://';
23d6bd09 269
270 /*
271 * If you have 'SSLOptions +StdEnvVars' in your apache config
272 * OR if you have HTTPS in your HTTP_SERVER_VARS
273 * OR if you are on port 443
274 */
c731b9f7 275 $getEnvVar = getenv('HTTPS');
276 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
277 (isset($HTTP_SERVER_VARS['HTTPS'])) ||
278 (isset($HTTP_SERVER_VARS['SERVER_PORT']) &&
279 $HTTP_SERVER_VARS['SERVER_PORT'] == 443)) {
8a549df2 280 $proto = 'https://';
1195c340 281 }
9374671f 282
1195c340 283 // Get the hostname from the Host header or server config.
8a549df2 284 $host = '';
23d6bd09 285 if (isset($HTTP_HOST) && !empty($HTTP_HOST)) {
b768a8eb 286 $host = $HTTP_HOST;
23d6bd09 287 } else if (isset($SERVER_NAME) && !empty($SERVER_NAME)) {
b768a8eb 288 $host = $SERVER_NAME;
289 }
9374671f 290
b768a8eb 291 $port = '';
23d6bd09 292 if (! strstr($host, ':')) {
b768a8eb 293 if (isset($SERVER_PORT)) {
8a549df2 294 if (($SERVER_PORT != 80 && $proto == 'http://')
295 || ($SERVER_PORT != 443 && $proto == 'https://')) {
b768a8eb 296 $port = sprintf(':%d', $SERVER_PORT);
297 }
298 }
299 }
9374671f 300
23d6bd09 301 /* Fallback is to omit the server name and use a relative */
302 /* URI, although this is not RFC 2616 compliant. */
303 return ($host ? $proto . $host . $port . $path : $path);
9374671f 304 }
7aaa81fc 305
52eefafc 306
23d6bd09 307 /**
308 * These functions are used to encrypt the passowrd before it is
309 * stored in a cookie.
310 */
59edd854 311 function OneTimePadEncrypt ($string, $epad) {
23d6bd09 312 $pad = base64_decode($epad);
313 $encrypted = '';
314 for ($i = 0; $i < strlen ($string); $i++) {
315 $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
316 }
52eefafc 317
23d6bd09 318 return base64_encode($encrypted);
52eefafc 319 }
320
59edd854 321 function OneTimePadDecrypt ($string, $epad) {
322 $pad = base64_decode($epad);
52eefafc 323 $encrypted = base64_decode ($string);
8a549df2 324 $decrypted = '';
52eefafc 325 for ($i = 0; $i < strlen ($encrypted); $i++) {
65f5b1c4 326 $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
52eefafc 327 }
328
329 return $decrypted;
330 }
331
580e1793 332
23d6bd09 333 /**
334 * Randomize the mt_rand() function. Toss this in strings or integers
335 * and it will seed the generator appropriately. With strings, it is
336 * better to get them long. Use md5() to lengthen smaller strings.
337 */
338 function sq_mt_seed($Val) {
dcaf2a49 339 // if mt_getrandmax() does not return a 2^n - 1 number,
340 // this might not work well. This uses $Max as a bitmask.
341 $Max = mt_getrandmax();
9374671f 342
23d6bd09 343 if (! is_int($Val)) {
344 if (function_exists('crc32')) {
dcaf2a49 345 $Val = crc32($Val);
23d6bd09 346 } else {
dcaf2a49 347 $Str = $Val;
348 $Pos = 0;
349 $Val = 0;
350 $Mask = $Max / 2;
351 $HighBit = $Max ^ $Mask;
23d6bd09 352 while ($Pos < strlen($Str)) {
353 if ($Val & $HighBit) {
dcaf2a49 354 $Val = (($Val & $Mask) << 1) + 1;
23d6bd09 355 } else {
dcaf2a49 356 $Val = ($Val & $Mask) << 1;
357 }
358 $Val ^= $Str[$Pos];
359 $Pos ++;
360 }
361 }
362 }
580e1793 363
23d6bd09 364 if ($Val < 0) {
365 $Val *= -1;
366 }
367
368 if ($Val = 0) {
369 return;
370 }
dcaf2a49 371
372 mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
373 }
9374671f 374
375
23d6bd09 376 /**
377 * This function initializes the random number generator fairly well.
378 * It also only initializes it once, so you don't accidentally get
379 * the same 'random' numbers twice in one session.
380 */
381 function sq_mt_randomize() {
dcaf2a49 382 global $REMOTE_PORT, $REMOTE_ADDR, $UNIQUE_ID;
383 static $randomized;
9374671f 384
23d6bd09 385 if ($randomized) {
386 return;
387 }
9374671f 388
23d6bd09 389 /* Global. */
dcaf2a49 390 sq_mt_seed((int)((double) microtime() * 1000000));
391 sq_mt_seed(md5($REMOTE_PORT . $REMOTE_ADDR . getmypid()));
9374671f 392
23d6bd09 393 /* getrusage */
8a549df2 394 if (function_exists('getrusage')) {
821a8e9c 395 // Avoid warnings with Win32
396 $dat = @getrusage();
23d6bd09 397 if (isset($dat) && is_array($dat)) {
821a8e9c 398 $Str = '';
399 foreach ($dat as $k => $v)
400 {
401 $Str .= $k . $v;
402 }
403 sq_mt_seed(md5($Str));
404 }
dcaf2a49 405 }
9374671f 406
dcaf2a49 407 // Apache-specific
408 sq_mt_seed(md5($UNIQUE_ID));
9374671f 409
dcaf2a49 410 $randomized = 1;
411 }
9374671f 412
dcaf2a49 413 function OneTimePadCreate ($length=100) {
414 sq_mt_randomize();
245a6892 415
8a549df2 416 $pad = '';
52eefafc 417 for ($i = 0; $i < $length; $i++) {
65f5b1c4 418 $pad .= chr(mt_rand(0,255));
52eefafc 419 }
420
59edd854 421 return base64_encode($pad);
52eefafc 422 }
423
23d6bd09 424 /**
425 * Check if we have a required PHP-version. Return TRUE if we do,
426 * or FALSE if we don't.
427 *
428 * To check for 4.0.1, use sqCheckPHPVersion(4,0,1)
429 * To check for 4.0b3, use sqCheckPHPVersion(4,0,-3)
430 *
431 * Does not handle betas like 4.0.1b1 or development versions
432 */
f79af863 433 function sqCheckPHPVersion($major, $minor, $release) {
434
435 $ver = phpversion();
5be8bbd8 436 eregi('^([0-9]+)\\.([0-9]+)(.*)', $ver, $regs);
f79af863 437
23d6bd09 438 /* Parse the version string. */
f79af863 439 $vmajor = strval($regs[1]);
440 $vminor = strval($regs[2]);
441 $vrel = $regs[3];
23d6bd09 442 if($vrel[0] == ".") {
65f5b1c4 443 $vrel = strval(substr($vrel, 1));
23d6bd09 444 }
445 if($vrel[0] == 'b' || $vrel[0] == 'B') {
65f5b1c4 446 $vrel = - strval(substr($vrel, 1));
23d6bd09 447 }
448 if($vrel[0] == 'r' || $vrel[0] == 'R') {
65f5b1c4 449 $vrel = - strval(substr($vrel, 2))/10;
23d6bd09 450 }
9374671f 451
23d6bd09 452 /* Compare major version. */
453 if ($vmajor < $major) { return false; }
454 if ($vmajor > $major) { return true; }
b5afdff0 455
23d6bd09 456 /* Major is the same. Compare minor. */
457 if ($vminor < $minor) { return false; }
458 if ($vminor > $minor) { return true; }
9374671f 459
23d6bd09 460 /* Major and minor is the same as the required one. Compare release */
461 if ($vrel >= 0 && $release >= 0) { // Neither are beta
65f5b1c4 462 if($vrel < $release) return false;
23d6bd09 463 } else if($vrel >= 0 && $release < 0) { // This is not beta, required is beta
65f5b1c4 464 return true;
23d6bd09 465 } else if($vrel < 0 && $release >= 0){ // This is beta, require not beta
65f5b1c4 466 return false;
23d6bd09 467 } else { // Both are beta
65f5b1c4 468 if($vrel > $release) return false;
f79af863 469 }
9374671f 470
f79af863 471 return true;
472 }
9374671f 473
23d6bd09 474 /**
475 * Returns a string showing the size of the message/attachment.
476 */
477 function show_readable_size($bytes) {
6e7468f6 478 $bytes /= 1024;
479 $type = 'k';
9374671f 480
23d6bd09 481 if ($bytes / 1024 > 1) {
6e7468f6 482 $bytes /= 1024;
483 $type = 'm';
484 }
9374671f 485
23d6bd09 486 if ($bytes < 10) {
6e7468f6 487 $bytes *= 10;
8a549df2 488 settype($bytes, 'integer');
6e7468f6 489 $bytes /= 10;
23d6bd09 490 } else {
8a549df2 491 settype($bytes, 'integer');
23d6bd09 492 }
9374671f 493
6e7468f6 494 return $bytes . '<small>&nbsp;' . $type . '</small>';
495 }
f79af863 496
23d6bd09 497 /**
498 * Generates a random string from the caracter set you pass in
1899535f 499 *
500 * Flags:
501 * 1 = add lowercase a-z to $chars
502 * 2 = add uppercase A-Z to $chars
503 * 4 = add numbers 0-9 to $chars
504 */
9374671f 505
23d6bd09 506 function GenerateRandomString($size, $chars, $flags = 0) {
507 if ($flags & 0x1) {
1899535f 508 $chars .= 'abcdefghijklmnopqrstuvwxyz';
23d6bd09 509 }
510 if ($flags & 0x2) {
1899535f 511 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
23d6bd09 512 }
513 if ($flags & 0x4) {
1899535f 514 $chars .= '0123456789';
23d6bd09 515 }
9374671f 516
23d6bd09 517 if (($size < 1) || (strlen($chars) < 1)) {
8a549df2 518 return '';
23d6bd09 519 }
9374671f 520
1899535f 521 sq_mt_randomize(); // Initialize the random number generator
9374671f 522
65f5b1c4 523 $String = "";
1899535f 524 while (strlen($String) < $size) {
525 $String .= $chars[mt_rand(0, strlen($chars))];
526 }
9374671f 527
1899535f 528 return $String;
529 }
9374671f 530
23d6bd09 531 function quoteIMAP($str) {
704db5b2 532 return ereg_replace('(["\\])', '\\\\1', $str);
533 }
1899535f 534
23d6bd09 535 /**
536 * Trims every element in the array
537 */
538 function TrimArray(&$array) {
539 foreach ($array as $k => $v) {
540 global $$k;
541 if (is_array($$k)) {
542 foreach ($$k as $k2 => $v2) {
543 $$k[$k2] = substr($v2, 1);
544 }
545 } else {
546 $$k = substr($v, 1);
547 }
548
549 /* Re-assign back to array. */
550 $array[$k] = $$k;
551 }
552 }
553
554 /**
555 * Removes slashes from every element in the array
556 */
557 function RemoveSlashes(&$array) {
558 foreach ($array as $k => $v) {
559 global $$k;
560 if (is_array($$k)) {
561 foreach ($$k as $k2 => $v2) {
562 $newArray[stripslashes($k2)] = stripslashes($v2);
563 }
564 $$k = $newArray;
565 } else {
566 $$k = stripslashes($v);
567 }
568
569 /* Re-assign back to the array. */
570 $array[$k] = $$k;
571 }
572 }
573
574?>