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