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