whoops.. didn't mean to commit this stuff
[squirrelmail.git] / functions / strings.php
CommitLineData
59177427 1<?php
2ef37ed4 2
3 /* $Id$ */
7ce342dc 4
d068c0ec 5 $strings_php = true;
6
3302d0d4 7 //*************************************************************************
8 // Count the number of occurances of $needle are in $haystack.
9 //*************************************************************************
10 function countCharInString($haystack, $needle) {
8a549df2 11 $haystack = ereg_replace("[^$needle]",'',$haystack);
f9b3e5d9 12 return strlen($haystack);
3302d0d4 13 }
14
15 //*************************************************************************
16 // Read from the back of $haystack until $needle is found, or the begining
f9b3e5d9 17 // of the $haystack is reached. $needle is a single character
3302d0d4 18 //*************************************************************************
19 function readShortMailboxName($haystack, $needle) {
8a549df2 20 if ($needle == '') return $haystack;
5be8bbd8 21 if ($needle == '.') $needle = '\\.';
1d2ce1c3 22 ereg("([^$needle]+)$needle?$", $haystack, $regs);
23 return $regs[1];
3302d0d4 24 }
25
5bdd7223 26 //*************************************************************************
27 // Read from the back of $haystack until $needle is found, or the begining
28 // of the $haystack is reached. $needle is a single character
29 //*************************************************************************
30 function readMailboxParent($haystack, $needle) {
5be8bbd8 31 if ($needle == '.') $needle = '\\.';
5bdd7223 32 ereg("^(.+)$needle([^$needle]+)$needle?$", $haystack, $regs);
33 return $regs[1];
34 }
35
8beafbbc 36 // Searches for the next position in a string minus white space
37 function next_pos_minus_white ($haystack, $pos) {
8a549df2 38 while (substr($haystack, $pos, 1) == ' ' ||
8beafbbc 39 substr($haystack, $pos, 1) == "\t" ||
40 substr($haystack, $pos, 1) == "\n" ||
41 substr($haystack, $pos, 1) == "\r") {
42 if ($pos >= strlen($haystack))
43 return -1;
44 $pos++;
45 }
46 return $pos;
47 }
48
8467bf00 49 // Wraps text at $wrap characters
a95681a7 50 // Has a problem with special HTML characters, so call this before
51 // you do character translation.
52 // Specifically, &#039 comes up as 5 characters instead of 1.
01aab860 53 // This should not add newlines to the end of lines.
9eea179c 54 function sqWordWrap(&$line, $wrap) {
5be8bbd8 55 preg_match('/^([\\s>]*)([^\\s>].*)?$/', $line, $regs);
45f6dd68 56 $beginning_spaces = $regs[1];
23fd3c8e 57 if (isset($regs[2])) {
58 $words = explode(' ', $regs[2]);
59 } else {
60 $words = "";
61 }
a95681a7 62
63 $i = 0;
64 $line = $beginning_spaces;
30f64711 65
bcad90fe 66 while ($i < count($words)) {
67 // Force one word to be on a line (minimum)
68 $line .= $words[$i];
48f8ce2f 69 $line_len = strlen($beginning_spaces) + strlen($words[$i]) + 2;
70 if (isset($words[$i + 1]))
71 $line_len += strlen($words[$i + 1]);
bcad90fe 72 $i ++;
45f6dd68 73
bcad90fe 74 // Add more words (as long as they fit)
75 while ($line_len < $wrap && $i < count($words)) {
76 $line .= ' ' . $words[$i];
77 $i++;
48f8ce2f 78 if (isset($words[$i]))
79 $line_len += strlen($words[$i]) + 1;
80 else
81 $line_len += 1;
bcad90fe 82 }
45f6dd68 83
bcad90fe 84 // Skip spaces if they are the first thing on a continued line
48f8ce2f 85 while (!isset($words[$i]) && $i < count($words)) {
bcad90fe 86 $i ++;
87 }
8ceb637a 88
89 // Go to the next line if we have more to process
bcad90fe 90 if ($i < count($words)) {
5be8bbd8 91 $line .= "\n" . $beginning_spaces;
b8ea4ed6 92 }
e550d551 93 }
e550d551 94 }
01aab860 95
96
97 // Does the opposite of sqWordWrap()
98 function sqUnWordWrap(&$body)
99 {
100 $lines = explode("\n", $body);
101 $body = "";
102 $PreviousSpaces = "";
103 for ($i = 0; $i < count($lines); $i ++)
104 {
5be8bbd8 105 preg_match('/^([\\s>]*)([^\\s>].*)?$/', $lines[$i], $regs);
01aab860 106 $CurrentSpaces = $regs[1];
48f8ce2f 107 if (isset($regs[2]))
108 $CurrentRest = $regs[2];
01aab860 109 if ($i == 0)
110 {
111 $PreviousSpaces = $CurrentSpaces;
112 $body = $lines[$i];
113 }
114 else if ($PreviousSpaces == $CurrentSpaces && // Do the beginnings match
115 strlen($lines[$i - 1]) > 65 && // Over 65 characters long
116 strlen($CurrentRest)) // and there's a line to continue with
117 {
118 $body .= ' ' . $CurrentRest;
119 }
120 else
121 {
122 $body .= "\n" . $lines[$i];
123 $PreviousSpaces = $CurrentSpaces;
124 }
125 }
126 $body .= "\n";
127 }
128
40ee9452 129
130 /** Returns an array of email addresses **/
a7f3c40d 131 /* Be cautious of "user@host.com" */
40ee9452 132 function parseAddrs($text) {
1d2ce1c3 133 if (trim($text) == "")
c5edd369 134 return array();
8a549df2 135 $text = str_replace(' ', '', $text);
136 $text = ereg_replace('"[^"]*"', '', $text);
5be8bbd8 137 $text = ereg_replace('\\([^\\)]*\\)', '', $text);
8a549df2 138 $text = str_replace(',', ';', $text);
139 $array = explode(';', $text);
1d2ce1c3 140 for ($i = 0; $i < count ($array); $i++) {
8a549df2 141 $array[$i] = eregi_replace ("^.*[<]", '', $array[$i]);
142 $array[$i] = eregi_replace ("[>].*$", '', $array[$i]);
1d2ce1c3 143 }
144 return $array;
40ee9452 145 }
146
147 /** Returns a line of comma separated email addresses from an array **/
148 function getLineOfAddrs($array) {
b676ba7e 149 if (is_array($array)) {
8a549df2 150 $to_line = implode(', ', $array);
151 $to_line = trim(ereg_replace(',,+', ',', $to_line));
b676ba7e 152 } else {
8a549df2 153 $to_line = '';
40ee9452 154 }
155 return $to_line;
156 }
7ce342dc 157
9eea179c 158 function translateText(&$body, $wrap_at, $charset) {
9297917e 159 global $where, $what; // from searching
172fd718 160 global $url_parser_php;
9297917e 161
8442ac08 162 if (!isset($url_parser_php)) {
8a549df2 163 include '../functions/url_parser.php';
8442ac08 164 }
165
a8648d75 166 $body_ary = explode("\n", $body);
8ceb637a 167 $PriorQuotes = 0;
8442ac08 168 for ($i=0; $i < count($body_ary); $i++) {
a8648d75 169 $line = $body_ary[$i];
a37f3771 170 if (strlen($line) - 2 >= $wrap_at) {
9eea179c 171 sqWordWrap($line, $wrap_at);
a37f3771 172 }
a95681a7 173 $line = charset_decode($charset, $line);
174 $line = str_replace("\t", ' ', $line);
a37f3771 175
9eea179c 176 parseUrl ($line);
e2ef6f4b 177
9eea179c 178 $Quotes = 0;
179 $pos = 0;
180 while (1)
181 {
8ceb637a 182 if ($line[$pos] == ' ')
9eea179c 183 {
8ceb637a 184 $pos ++;
9eea179c 185 }
186 else if (strpos($line, '&gt;', $pos) === $pos)
187 {
188 $pos += 4;
189 $Quotes ++;
190 }
191 else
192 {
193 break;
194 }
195 }
196
8ceb637a 197 if ($Quotes > 1)
ccc4b58b 198 $line = '<FONT COLOR="FF0000">'.$line.'</FONT>';
8ceb637a 199 elseif ($Quotes)
ccc4b58b 200 $line = '<FONT COLOR="800000">'.$line.'</FONT>';
e2ef6f4b 201
8ceb637a 202 $body_ary[$i] = $line;
a8648d75 203 }
8a549df2 204 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
78509c54 205 }
206
7ce342dc 207 /* SquirrelMail version number -- DO NOT CHANGE */
8a549df2 208 $version = '1.0.1 [cvs]';
d29aac0e 209
210
211 function find_mailbox_name ($mailbox) {
f9b3e5d9 212 if (ereg(" *\"([^\r\n\"]*)\"[ \r\n]*$", $mailbox, $regs))
213 return $regs[1];
214 ereg(" *([^ \r\n\"]*)[ \r\n]*$",$mailbox,$regs);
215 return $regs[1];
216
d29aac0e 217 }
218
219 function replace_spaces ($string) {
8a549df2 220 return str_replace(' ', '&nbsp;', $string);
d29aac0e 221 }
222
223 function replace_escaped_spaces ($string) {
8a549df2 224 return str_replace('&nbsp;', ' ', $string);
d29aac0e 225 }
1195c340 226
227 function get_location () {
228 # This determines the location to forward to relative
7e343a7d 229 # to your server. If this doesnt work correctly for
1195c340 230 # you (although it should), you can remove all this
231 # code except the last two lines, and change the header()
232 # function to look something like this, customized to
233 # the location of SquirrelMail on your server:
234 #
235 # http://www.myhost.com/squirrelmail/src/login.php
236
00421cb6 237 global $PHP_SELF, $SERVER_NAME, $HTTPS, $HTTP_HOST, $SERVER_PORT;
1195c340 238
239 // Get the path
240 $path = substr($PHP_SELF, 0, strrpos($PHP_SELF, '/'));
241
242 // Check if this is a HTTPS or regular HTTP request
8a549df2 243 $proto = 'http://';
16f32d4a 244 if(isset($HTTPS) && !strcasecmp($HTTPS, 'on') ) {
8a549df2 245 $proto = 'https://';
1195c340 246 }
247
248 // Get the hostname from the Host header or server config.
8a549df2 249 $host = '';
b768a8eb 250 if (isset($HTTP_HOST) && !empty($HTTP_HOST))
251 {
252 $host = $HTTP_HOST;
253 }
254 else if (isset($SERVER_NAME) && !empty($SERVER_NAME))
255 {
256 $host = $SERVER_NAME;
257 }
258
b768a8eb 259 $port = '';
260 if (! strstr($host, ':'))
261 {
262 if (isset($SERVER_PORT)) {
8a549df2 263 if (($SERVER_PORT != 80 && $proto == 'http://')
264 || ($SERVER_PORT != 443 && $proto == 'https://')) {
b768a8eb 265 $port = sprintf(':%d', $SERVER_PORT);
266 }
267 }
268 }
269
270 if ($host)
271 return $proto . $host . $port . $path;
272
1195c340 273 // Fallback is to omit the server name and use a relative URI,
274 // although this is not RFC 2616 compliant.
b768a8eb 275 return $path;
1195c340 276 }
7aaa81fc 277
278 function sqStripSlashes($string) {
279 if (get_magic_quotes_gpc()) {
280 $string = stripslashes($string);
281 }
282 return $string;
283 }
52eefafc 284
285
286 // These functions are used to encrypt the passowrd before it is
287 // stored in a cookie.
59edd854 288 function OneTimePadEncrypt ($string, $epad) {
289 $pad = base64_decode($epad);
8a549df2 290 $encrypted = '';
52eefafc 291 for ($i = 0; $i < strlen ($string); $i++) {
292 $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
293 }
294
295 return base64_encode($encrypted);
296 }
297
59edd854 298 function OneTimePadDecrypt ($string, $epad) {
299 $pad = base64_decode($epad);
52eefafc 300 $encrypted = base64_decode ($string);
8a549df2 301 $decrypted = '';
52eefafc 302 for ($i = 0; $i < strlen ($encrypted); $i++) {
303 $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
304 }
305
306 return $decrypted;
307 }
308
580e1793 309
dcaf2a49 310 // Randomize the mt_rand() function. Toss this in strings or
311 // integers and it will seed the generator appropriately.
312 // With strings, it is better to get them long. Use md5() to
313 // lengthen smaller strings.
314 function sq_mt_seed($Val)
315 {
316 // if mt_getrandmax() does not return a 2^n - 1 number,
317 // this might not work well. This uses $Max as a bitmask.
318 $Max = mt_getrandmax();
319
320 if (! is_int($Val))
321 {
8a549df2 322 if (function_exists('crc32'))
dcaf2a49 323 {
324 $Val = crc32($Val);
325 }
326 else
327 {
328 $Str = $Val;
329 $Pos = 0;
330 $Val = 0;
331 $Mask = $Max / 2;
332 $HighBit = $Max ^ $Mask;
333 while ($Pos < strlen($Str))
334 {
335 if ($Val & $HighBit)
336 {
337 $Val = (($Val & $Mask) << 1) + 1;
338 }
339 else
340 {
341 $Val = ($Val & $Mask) << 1;
342 }
343 $Val ^= $Str[$Pos];
344 $Pos ++;
345 }
346 }
347 }
580e1793 348
dcaf2a49 349 if ($Val < 0)
350 $Val *= -1;
351 if ($Val = 0)
352 return;
353
354 mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
355 }
356
357
358 // This function initializes the random number generator fairly well.
359 // It also only initializes it once, so you don't accidentally get
360 // the same 'random' numbers twice in one session.
361 function sq_mt_randomize()
362 {
363 global $REMOTE_PORT, $REMOTE_ADDR, $UNIQUE_ID;
364 static $randomized;
365
366 if ($randomized)
367 return;
368
369 // Global
370 sq_mt_seed((int)((double) microtime() * 1000000));
371 sq_mt_seed(md5($REMOTE_PORT . $REMOTE_ADDR . getmypid()));
372
373 // getrusage
8a549df2 374 if (function_exists('getrusage')) {
dcaf2a49 375 $dat = getrusage();
8a549df2 376 $Str = '';
245a6892 377 foreach ($dat as $k => $v)
378 {
5be8bbd8 379 $Str .= $k . $v;
245a6892 380 }
381 sq_mt_seed(md5($Str));
dcaf2a49 382 }
383
384 // Apache-specific
385 sq_mt_seed(md5($UNIQUE_ID));
386
387 $randomized = 1;
388 }
389
390 function OneTimePadCreate ($length=100) {
391 sq_mt_randomize();
245a6892 392
8a549df2 393 $pad = '';
52eefafc 394 for ($i = 0; $i < $length; $i++) {
dcaf2a49 395 $pad .= chr(mt_rand(0,255));
52eefafc 396 }
397
59edd854 398 return base64_encode($pad);
52eefafc 399 }
400
f79af863 401 // Check if we have a required PHP-version. Return TRUE if we do,
402 // or FALSE if we don't.
403 // To check for 4.0.1, use sqCheckPHPVersion(4,0,1)
404 // To check for 4.0b3, use sqCheckPHPVersion(4,0,-3)
405 // Does not handle betas like 4.0.1b1 or development versions
406 function sqCheckPHPVersion($major, $minor, $release) {
407
408 $ver = phpversion();
5be8bbd8 409 eregi('^([0-9]+)\\.([0-9]+)(.*)', $ver, $regs);
f79af863 410
411 // Parse the version string
412 $vmajor = strval($regs[1]);
413 $vminor = strval($regs[2]);
414 $vrel = $regs[3];
415 if($vrel[0] == ".")
416 $vrel = strval(substr($vrel, 1));
8a549df2 417 if($vrel[0] == 'b' || $vrel[0] == 'B')
f79af863 418 $vrel = - strval(substr($vrel, 1));
8a549df2 419 if($vrel[0] == 'r' || $vrel[0] == 'R')
f79af863 420 $vrel = - strval(substr($vrel, 2))/10;
421
b5afdff0 422 // Compare major version
f79af863 423 if($vmajor < $major) return false;
b5afdff0 424 if($vmajor > $major) return true;
425
426 // Major is the same. Compare minor
f79af863 427 if($vminor < $minor) return false;
b5afdff0 428 if($vminor > $minor) return true;
f79af863 429
b5afdff0 430 // Major and minor is the same as the required one.
f79af863 431 // Compare release
432 if($vrel >= 0 && $release >= 0) { // Neither are beta
433 if($vrel < $release) return false;
434 } else if($vrel >= 0 && $release < 0){ // This is not beta, required is beta
435 return true;
436 } else if($vrel < 0 && $release >= 0){ // This is beta, require not beta
437 return false;
438 } else { // Both are beta
439 if($vrel > $release) return false;
440 }
441
442 return true;
443 }
6e7468f6 444
445 /* Returns a string showing the size of the message/attachment */
446 function show_readable_size($bytes)
447 {
448 $bytes /= 1024;
449 $type = 'k';
450
451 if ($bytes / 1024 > 1)
452 {
453 $bytes /= 1024;
454 $type = 'm';
455 }
456
457 if ($bytes < 10)
458 {
459 $bytes *= 10;
8a549df2 460 settype($bytes, 'integer');
6e7468f6 461 $bytes /= 10;
462 }
463 else
8a549df2 464 settype($bytes, 'integer');
6e7468f6 465
466 return $bytes . '<small>&nbsp;' . $type . '</small>';
467 }
f79af863 468
1899535f 469 /* Generates a random string from the caracter set you pass in
470 *
471 * Flags:
472 * 1 = add lowercase a-z to $chars
473 * 2 = add uppercase A-Z to $chars
474 * 4 = add numbers 0-9 to $chars
475 */
476
477 function GenerateRandomString($size, $chars, $flags = 0)
478 {
479 if ($flags & 0x1)
480 $chars .= 'abcdefghijklmnopqrstuvwxyz';
481 if ($flags & 0x2)
482 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
483 if ($flags & 0x4)
484 $chars .= '0123456789';
485
486 if ($size < 1 || strlen($chars) < 1)
8a549df2 487 return '';
1899535f 488
489 sq_mt_randomize(); // Initialize the random number generator
490
ccc4b58b 491 $String = "";
1899535f 492 while (strlen($String) < $size) {
493 $String .= $chars[mt_rand(0, strlen($chars))];
494 }
495
496 return $String;
497 }
498
ccc4b58b 499?>