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