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