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