minor version changes and updates
[squirrelmail.git] / functions / strings.php
1 <?php
2
3 /* $Id$ */
4
5 $strings_php = true;
6
7 //*************************************************************************
8 // Count the number of occurances of $needle are in $haystack.
9 //*************************************************************************
10 function countCharInString($haystack, $needle) {
11 $haystack = ereg_replace("[^$needle]","",$haystack);
12 return strlen($haystack);
13 }
14
15 //*************************************************************************
16 // Read from the back of $haystack until $needle is found, or the begining
17 // of the $haystack is reached. $needle is a single character
18 //*************************************************************************
19 function readShortMailboxName($haystack, $needle) {
20 if ($needle == "") return $haystack;
21 if ($needle == ".") $needle = "\.";
22 ereg("([^$needle]+)$needle?$", $haystack, $regs);
23 return $regs[1];
24 }
25
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) {
31 if ($needle == ".") $needle = "\.";
32 ereg("^(.+)$needle([^$needle]+)$needle?$", $haystack, $regs);
33 return $regs[1];
34 }
35
36 // Searches for the next position in a string minus white space
37 function next_pos_minus_white ($haystack, $pos) {
38 while (substr($haystack, $pos, 1) == " " ||
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
49 // Wraps text at $wrap characters
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.
53 // This should not add newlines to the end of lines.
54 function sqWordWrap(&$line, $wrap) {
55 preg_match("/^([\s>]*)([^\s>].*)?$/", $line, $regs);
56 $beginning_spaces = $regs[1];
57 $words = explode(" ", $regs[2]);
58
59 $i = 0;
60 $line = $beginning_spaces;
61
62 while ($i < count($words)) {
63 // Force one word to be on a line (minimum)
64 $line .= $words[$i];
65 $line_len = strlen($beginning_spaces) + strlen($words[$i]) + 2;
66 if (isset($words[$i + 1]))
67 $line_len += strlen($words[$i + 1]);
68 $i ++;
69
70 // Add more words (as long as they fit)
71 while ($line_len < $wrap && $i < count($words)) {
72 $line .= ' ' . $words[$i];
73 $i++;
74 if (isset($words[$i]))
75 $line_len += strlen($words[$i]) + 1;
76 else
77 $line_len += 1;
78 }
79
80 // Skip spaces if they are the first thing on a continued line
81 while (!isset($words[$i]) && $i < count($words)) {
82 $i ++;
83 }
84
85 // Go to the next line if we have more to process
86 if ($i < count($words)) {
87 $line .= "\n$beginning_spaces";
88 }
89 }
90 }
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];
103 if (isset($regs[2]))
104 $CurrentRest = $regs[2];
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
125
126 /** Returns an array of email addresses **/
127 /* Be cautious of "user@host.com" */
128 function parseAddrs($text) {
129 if (trim($text) == "")
130 return array();
131 $text = str_replace(" ", "", $text);
132 $text = ereg_replace('"[^"]*"', "", $text);
133 $text = ereg_replace("\([^\)]*\)", "", $text);
134 $text = str_replace(",", ";", $text);
135 $array = explode(";", $text);
136 for ($i = 0; $i < count ($array); $i++) {
137 $array[$i] = eregi_replace ("^.*[<]", "", $array[$i]);
138 $array[$i] = eregi_replace ("[>].*$", "", $array[$i]);
139 }
140 return $array;
141 }
142
143 /** Returns a line of comma separated email addresses from an array **/
144 function getLineOfAddrs($array) {
145 if (is_array($array)) {
146 $to_line = implode(", ", $array);
147 $to_line = trim(ereg_replace(",,+", ",", $to_line));
148 } else {
149 $to_line = "";
150 }
151 return $to_line;
152 }
153
154 function translateText(&$body, $wrap_at, $charset) {
155 global $where, $what; // from searching
156 global $url_parser_php;
157
158 if (!isset($url_parser_php)) {
159 include "../functions/url_parser.php";
160 }
161
162 $body_ary = explode("\n", $body);
163 $PriorQuotes = 0;
164 for ($i=0; $i < count($body_ary); $i++) {
165 $line = $body_ary[$i];
166 if (strlen($line) - 2 >= $wrap_at) {
167 sqWordWrap($line, $wrap_at);
168 }
169 $line = charset_decode($charset, $line);
170 $line = str_replace("\t", ' ', $line);
171
172 parseUrl ($line);
173
174 $Quotes = 0;
175 $pos = 0;
176 while (1)
177 {
178 if ($line[$pos] == ' ')
179 {
180 $pos ++;
181 }
182 else if (strpos($line, '&gt;', $pos) === $pos)
183 {
184 $pos += 4;
185 $Quotes ++;
186 }
187 else
188 {
189 break;
190 }
191 }
192
193 if ($Quotes > 1)
194 $line = "<FONT COLOR=FF0000>$line</FONT>";
195 elseif ($Quotes)
196 $line = "<FONT COLOR=800000>$line</FONT>";
197
198 $body_ary[$i] = $line;
199 }
200 $body = "<pre>" . implode("\n", $body_ary) . "</pre>";
201 }
202
203 /* SquirrelMail version number -- DO NOT CHANGE */
204 $version = "1.0.1 [cvs]";
205
206
207 function find_mailbox_name ($mailbox) {
208 /*
209 $mailbox = trim($mailbox);
210 if (substr($mailbox, strlen($mailbox)-1, strlen($mailbox)) == "\"") {
211 $mailbox = substr($mailbox, 0, strlen($mailbox) - 1);
212 $pos = strrpos ($mailbox, "\"")+1;
213 $box = substr($mailbox, $pos);
214 } else {
215 $box = substr($mailbox, strrpos($mailbox, " ")+1, strlen($mailbox));
216 }
217 return $box;
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
225 }
226
227 function replace_spaces ($string) {
228 return str_replace(" ", "&nbsp;", $string);
229 }
230
231 function replace_escaped_spaces ($string) {
232 return str_replace("&nbsp;", " ", $string);
233 }
234
235 function get_location () {
236 # This determines the location to forward to relative
237 # to your server. If this doesnt work correctly for
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
245 global $PHP_SELF, $SERVER_NAME, $HTTPS, $HTTP_HOST, $SERVER_PORT;
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
251 $proto = "http://";
252 if(isset($HTTPS) && !strcasecmp($HTTPS, 'on') ) {
253 $proto = "https://";
254 }
255
256 // Get the hostname from the Host header or server config.
257 $host = "";
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
267 $port = '';
268 if (! strstr($host, ':'))
269 {
270 if (isset($SERVER_PORT)) {
271 if (($SERVER_PORT != 80 && $proto == "http://")
272 || ($SERVER_PORT != 443 && $proto == "https://")) {
273 $port = sprintf(':%d', $SERVER_PORT);
274 }
275 }
276 }
277
278 if ($host)
279 return $proto . $host . $port . $path;
280
281 // Fallback is to omit the server name and use a relative URI,
282 // although this is not RFC 2616 compliant.
283 return $path;
284 }
285
286 function sqStripSlashes($string) {
287 if (get_magic_quotes_gpc()) {
288 $string = stripslashes($string);
289 }
290 return $string;
291 }
292
293
294 // These functions are used to encrypt the passowrd before it is
295 // stored in a cookie.
296 function OneTimePadEncrypt ($string, $epad) {
297 $pad = base64_decode($epad);
298 $encrypted = "";
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
306 function OneTimePadDecrypt ($string, $epad) {
307 $pad = base64_decode($epad);
308 $encrypted = base64_decode ($string);
309 $decrypted = "";
310 for ($i = 0; $i < strlen ($encrypted); $i++) {
311 $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
312 }
313
314 return $decrypted;
315 }
316
317
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 {
330 if (function_exists("crc32"))
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 }
356
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
382 if (function_exists("getrusage")) {
383 $dat = getrusage();
384 $Str = "";
385 foreach ($dat as $k => $v)
386 {
387 $Str .= "$k = $v\n";
388 }
389 sq_mt_seed(md5($Str));
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();
400
401 $pad = "";
402 for ($i = 0; $i < $length; $i++) {
403 $pad .= chr(mt_rand(0,255));
404 }
405
406 return base64_encode($pad);
407 }
408
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));
425 if($vrel[0] == "b" || $vrel[0] == "B")
426 $vrel = - strval(substr($vrel, 1));
427 if($vrel[0] == "r" || $vrel[0] == "R")
428 $vrel = - strval(substr($vrel, 2))/10;
429
430 // Compare major version
431 if($vmajor < $major) return false;
432 if($vmajor > $major) return true;
433
434 // Major is the same. Compare minor
435 if($vminor < $minor) return false;
436 if($vminor > $minor) return true;
437
438 // Major and minor is the same as the required one.
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 }
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;
468 settype($bytes, "integer");
469 $bytes /= 10;
470 }
471 else
472 settype($bytes, "integer");
473
474 return $bytes . '<small>&nbsp;' . $type . '</small>';
475 }
476
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)
495 return "";
496
497 sq_mt_randomize(); // Initialize the random number generator
498
499 while (strlen($String) < $size) {
500 $String .= $chars[mt_rand(0, strlen($chars))];
501 }
502
503 return $String;
504 }
505
506 ?>