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