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