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