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