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