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