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