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