* Auto-detects if form is 'compose.php' and if PHP is giving us bad form
[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.2 [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 function replace_spaces ($string) {
304 return str_replace(' ', '&nbsp;', $string);
305 }
306
307 function replace_escaped_spaces ($string) {
308 return str_replace('&nbsp;', ' ', $string);
309 }
310
311 function get_location () {
312 # This determines the location to forward to relative
313 # to your server. If this doesnt work correctly for
314 # you (although it should), you can remove all this
315 # code except the last two lines, and change the header()
316 # function to look something like this, customized to
317 # the location of SquirrelMail on your server:
318 #
319 # http://www.myhost.com/squirrelmail/src/login.php
320
321 global $PHP_SELF, $SERVER_NAME, $HTTPS, $HTTP_HOST, $SERVER_PORT;
322
323 // Get the path
324 $path = substr($PHP_SELF, 0, strrpos($PHP_SELF, '/'));
325
326 // Check if this is a HTTPS or regular HTTP request
327 $proto = 'http://';
328 if(isset($HTTPS) && !strcasecmp($HTTPS, 'on') ) {
329 $proto = 'https://';
330 }
331
332 // Get the hostname from the Host header or server config.
333 $host = '';
334 if (isset($HTTP_HOST) && !empty($HTTP_HOST))
335 {
336 $host = $HTTP_HOST;
337 }
338 else if (isset($SERVER_NAME) && !empty($SERVER_NAME))
339 {
340 $host = $SERVER_NAME;
341 }
342
343 $port = '';
344 if (! strstr($host, ':'))
345 {
346 if (isset($SERVER_PORT)) {
347 if (($SERVER_PORT != 80 && $proto == 'http://')
348 || ($SERVER_PORT != 443 && $proto == 'https://')) {
349 $port = sprintf(':%d', $SERVER_PORT);
350 }
351 }
352 }
353
354 if ($host)
355 return $proto . $host . $port . $path;
356
357 // Fallback is to omit the server name and use a relative URI,
358 // although this is not RFC 2616 compliant.
359 return $path;
360 }
361
362
363 // These functions are used to encrypt the passowrd before it is
364 // stored in a cookie.
365 function OneTimePadEncrypt ($string, $epad) {
366 $pad = base64_decode($epad);
367 $encrypted = '';
368 for ($i = 0; $i < strlen ($string); $i++) {
369 $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
370 }
371
372 return base64_encode($encrypted);
373 }
374
375 function OneTimePadDecrypt ($string, $epad) {
376 $pad = base64_decode($epad);
377 $encrypted = base64_decode ($string);
378 $decrypted = '';
379 for ($i = 0; $i < strlen ($encrypted); $i++) {
380 $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
381 }
382
383 return $decrypted;
384 }
385
386
387 // Randomize the mt_rand() function. Toss this in strings or
388 // integers and it will seed the generator appropriately.
389 // With strings, it is better to get them long. Use md5() to
390 // lengthen smaller strings.
391 function sq_mt_seed($Val)
392 {
393 // if mt_getrandmax() does not return a 2^n - 1 number,
394 // this might not work well. This uses $Max as a bitmask.
395 $Max = mt_getrandmax();
396
397 if (! is_int($Val))
398 {
399 if (function_exists('crc32'))
400 {
401 $Val = crc32($Val);
402 }
403 else
404 {
405 $Str = $Val;
406 $Pos = 0;
407 $Val = 0;
408 $Mask = $Max / 2;
409 $HighBit = $Max ^ $Mask;
410 while ($Pos < strlen($Str))
411 {
412 if ($Val & $HighBit)
413 {
414 $Val = (($Val & $Mask) << 1) + 1;
415 }
416 else
417 {
418 $Val = ($Val & $Mask) << 1;
419 }
420 $Val ^= $Str[$Pos];
421 $Pos ++;
422 }
423 }
424 }
425
426 if ($Val < 0)
427 $Val *= -1;
428 if ($Val = 0)
429 return;
430
431 mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
432 }
433
434
435 // This function initializes the random number generator fairly well.
436 // It also only initializes it once, so you don't accidentally get
437 // the same 'random' numbers twice in one session.
438 function sq_mt_randomize()
439 {
440 global $REMOTE_PORT, $REMOTE_ADDR, $UNIQUE_ID;
441 static $randomized;
442
443 if ($randomized)
444 return;
445
446 // Global
447 sq_mt_seed((int)((double) microtime() * 1000000));
448 sq_mt_seed(md5($REMOTE_PORT . $REMOTE_ADDR . getmypid()));
449
450 // getrusage
451 if (function_exists('getrusage')) {
452 $dat = getrusage();
453 $Str = '';
454 foreach ($dat as $k => $v)
455 {
456 $Str .= $k . $v;
457 }
458 sq_mt_seed(md5($Str));
459 }
460
461 // Apache-specific
462 sq_mt_seed(md5($UNIQUE_ID));
463
464 $randomized = 1;
465 }
466
467 function OneTimePadCreate ($length=100) {
468 sq_mt_randomize();
469
470 $pad = '';
471 for ($i = 0; $i < $length; $i++) {
472 $pad .= chr(mt_rand(0,255));
473 }
474
475 return base64_encode($pad);
476 }
477
478 // Check if we have a required PHP-version. Return TRUE if we do,
479 // or FALSE if we don't.
480 // To check for 4.0.1, use sqCheckPHPVersion(4,0,1)
481 // To check for 4.0b3, use sqCheckPHPVersion(4,0,-3)
482 // Does not handle betas like 4.0.1b1 or development versions
483 function sqCheckPHPVersion($major, $minor, $release) {
484
485 $ver = phpversion();
486 eregi('^([0-9]+)\\.([0-9]+)(.*)', $ver, $regs);
487
488 // Parse the version string
489 $vmajor = strval($regs[1]);
490 $vminor = strval($regs[2]);
491 $vrel = $regs[3];
492 if($vrel[0] == ".")
493 $vrel = strval(substr($vrel, 1));
494 if($vrel[0] == 'b' || $vrel[0] == 'B')
495 $vrel = - strval(substr($vrel, 1));
496 if($vrel[0] == 'r' || $vrel[0] == 'R')
497 $vrel = - strval(substr($vrel, 2))/10;
498
499 // Compare major version
500 if($vmajor < $major) return false;
501 if($vmajor > $major) return true;
502
503 // Major is the same. Compare minor
504 if($vminor < $minor) return false;
505 if($vminor > $minor) return true;
506
507 // Major and minor is the same as the required one.
508 // Compare release
509 if($vrel >= 0 && $release >= 0) { // Neither are beta
510 if($vrel < $release) return false;
511 } else if($vrel >= 0 && $release < 0){ // This is not beta, required is beta
512 return true;
513 } else if($vrel < 0 && $release >= 0){ // This is beta, require not beta
514 return false;
515 } else { // Both are beta
516 if($vrel > $release) return false;
517 }
518
519 return true;
520 }
521
522 /* Returns a string showing the size of the message/attachment */
523 function show_readable_size($bytes)
524 {
525 $bytes /= 1024;
526 $type = 'k';
527
528 if ($bytes / 1024 > 1)
529 {
530 $bytes /= 1024;
531 $type = 'm';
532 }
533
534 if ($bytes < 10)
535 {
536 $bytes *= 10;
537 settype($bytes, 'integer');
538 $bytes /= 10;
539 }
540 else
541 settype($bytes, 'integer');
542
543 return $bytes . '<small>&nbsp;' . $type . '</small>';
544 }
545
546 /* Generates a random string from the caracter set you pass in
547 *
548 * Flags:
549 * 1 = add lowercase a-z to $chars
550 * 2 = add uppercase A-Z to $chars
551 * 4 = add numbers 0-9 to $chars
552 */
553
554 function GenerateRandomString($size, $chars, $flags = 0)
555 {
556 if ($flags & 0x1)
557 $chars .= 'abcdefghijklmnopqrstuvwxyz';
558 if ($flags & 0x2)
559 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
560 if ($flags & 0x4)
561 $chars .= '0123456789';
562
563 if ($size < 1 || strlen($chars) < 1)
564 return '';
565
566 sq_mt_randomize(); // Initialize the random number generator
567
568 $String = "";
569 while (strlen($String) < $size) {
570 $String .= $chars[mt_rand(0, strlen($chars))];
571 }
572
573 return $String;
574 }
575
576 ?>