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