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