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