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