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