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