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