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