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