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