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