10f896f4b067084a18a10fb3e6af4221b8ff2704
[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 $len = strlen($haystack);
10 for ($i = 0; $i < $len; $i++) {
11 if ($haystack[$i] == $needle)
12 $count++;
13 }
14 return $count;
15 }
16
17 //*************************************************************************
18 // Read from the back of $haystack until $needle is found, or the begining
19 // of the $haystack is reached.
20 //*************************************************************************
21 function readShortMailboxName($haystack, $needle) {
22 if (substr($haystack, -1) == $needle)
23 $haystack = substr($haystack, 0, strlen($haystack) - 1);
24
25 if (strrpos($haystack, $needle)) {
26 $pos = strrpos($haystack, $needle) + 1;
27 $data = substr($haystack, $pos, strlen($haystack));
28 } else {
29 $data = $haystack;
30 }
31 return $data;
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 if ($i < count($words)) {
80 $line .= "\n$beginning_spaces";
81 }
82 }
83 }
84
85
86 // Does the opposite of sqWordWrap()
87 function sqUnWordWrap(&$body)
88 {
89 $lines = explode("\n", $body);
90 $body = "";
91 $PreviousSpaces = "";
92 for ($i = 0; $i < count($lines); $i ++)
93 {
94 preg_match("/^([\s>]*)([^\s>].*)?$/", $lines[$i], $regs);
95 $CurrentSpaces = $regs[1];
96 $CurrentRest = $regs[2];
97 if ($i == 0)
98 {
99 $PreviousSpaces = $CurrentSpaces;
100 $body = $lines[$i];
101 }
102 else if ($PreviousSpaces == $CurrentSpaces && // Do the beginnings match
103 strlen($lines[$i - 1]) > 65 && // Over 65 characters long
104 strlen($CurrentRest)) // and there's a line to continue with
105 {
106 $body .= ' ' . $CurrentRest;
107 }
108 else
109 {
110 $body .= "\n" . $lines[$i];
111 $PreviousSpaces = $CurrentSpaces;
112 }
113 }
114 $body .= "\n";
115 }
116
117
118 /** Returns an array of email addresses **/
119 function parseAddrs($text) {
120 if (trim($text) == "") {
121 return;
122 }
123 $text = str_replace(" ", "", $text);
124 $text = ereg_replace( '"[^"]*"', "", $text);
125 $text = str_replace(",", ";", $text);
126 $array = explode(";", $text);
127 for ($i = 0; $i < count ($array); $i++) {
128 $array[$i] = eregi_replace ("^.*[<]", "", $array[$i]);
129 $array[$i] = eregi_replace ("[>].*$", "", $array[$i]);
130 }
131 return $array;
132 }
133
134 /** Returns a line of comma separated email addresses from an array **/
135 function getLineOfAddrs($array) {
136 if (is_array($array)) {
137 $to_line = implode(", ", $array);
138 $to_line = trim(ereg_replace(",,+", ",", $to_line));
139 } else {
140 $to_line = "";
141 }
142 return $to_line;
143 }
144
145 function translateText(&$body, $wrap_at, $charset) {
146 global $where, $what; // from searching
147
148 if (!isset($url_parser_php)) {
149 include "../functions/url_parser.php";
150 }
151
152 $body_ary = explode("\n", $body);
153 for ($i=0; $i < count($body_ary); $i++) {
154 $line = $body_ary[$i];
155 if (strlen($line) - 2 >= $wrap_at) {
156 sqWordWrap($line, $wrap_at);
157 }
158 $line = charset_decode($charset, $line);
159 $line = str_replace("\t", ' ', $line);
160
161 // We need to do it twice to catch times where there
162 // are an odd number of spaces
163 $line = str_replace(' ', '&nbsp; ', $line);
164 $line = str_replace(' ', '&nbsp; ', $line);
165 $line = nl2br($line);
166
167 parseUrl ($line);
168
169 $Quotes = 0;
170 $pos = 0;
171 while (1)
172 {
173 if (strpos($line, '&nbsp;', $pos) === $pos)
174 {
175 $pos += 6;
176 }
177 else if (strpos($line, '&gt;', $pos) === $pos)
178 {
179 $pos += 4;
180 $Quotes ++;
181 }
182 else
183 {
184 break;
185 }
186 }
187
188 if ($Quotes > 1) {
189 $line = "<FONT COLOR=FF0000>$line</FONT>\n";
190 } else if ($Quotes) {
191 $line = "<FONT COLOR=800000>$line</FONT>\n";
192 }
193
194 if ($line)
195 {
196 $line = '<tt>' . $line . '</tt>';
197 }
198
199 $body_ary[$i] = $line . '<br>';
200 }
201 $body = implode("\n", $body_ary);
202 }
203
204 /* SquirrelMail version number -- DO NOT CHANGE */
205 $version = "0.6pre1 (cvs)";
206
207
208 function find_mailbox_name ($mailbox) {
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 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) {
265 $port = sprintf(':%d', $SERVER_PORT);
266 }
267 }
268 }
269
270 if ($host)
271 return $proto . $host . $port . $path;
272
273 // Fallback is to omit the server name and use a relative URI,
274 // although this is not RFC 2616 compliant.
275 return $path;
276 }
277
278 function sqStripSlashes($string) {
279 if (get_magic_quotes_gpc()) {
280 $string = stripslashes($string);
281 }
282 return $string;
283 }
284
285
286 // These functions are used to encrypt the passowrd before it is
287 // stored in a cookie.
288 function OneTimePadEncrypt ($string, $pad) {
289 for ($i = 0; $i < strlen ($string); $i++) {
290 $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
291 }
292
293 return base64_encode($encrypted);
294 }
295
296 function OneTimePadDecrypt ($string, $pad) {
297 $encrypted = base64_decode ($string);
298
299 for ($i = 0; $i < strlen ($encrypted); $i++) {
300 $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
301 }
302
303 return $decrypted;
304 }
305
306
307 // Randomize the mt_rand() function. Toss this in strings or
308 // integers and it will seed the generator appropriately.
309 // With strings, it is better to get them long. Use md5() to
310 // lengthen smaller strings.
311 function sq_mt_seed($Val)
312 {
313 // if mt_getrandmax() does not return a 2^n - 1 number,
314 // this might not work well. This uses $Max as a bitmask.
315 $Max = mt_getrandmax();
316
317 if (! is_int($Val))
318 {
319 if (function_exists("crc32"))
320 {
321 $Val = crc32($Val);
322 }
323 else
324 {
325 $Str = $Val;
326 $Pos = 0;
327 $Val = 0;
328 $Mask = $Max / 2;
329 $HighBit = $Max ^ $Mask;
330 while ($Pos < strlen($Str))
331 {
332 if ($Val & $HighBit)
333 {
334 $Val = (($Val & $Mask) << 1) + 1;
335 }
336 else
337 {
338 $Val = ($Val & $Mask) << 1;
339 }
340 $Val ^= $Str[$Pos];
341 $Pos ++;
342 }
343 }
344 }
345
346 if ($Val < 0)
347 $Val *= -1;
348 if ($Val = 0)
349 return;
350
351 mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
352 }
353
354
355 // This function initializes the random number generator fairly well.
356 // It also only initializes it once, so you don't accidentally get
357 // the same 'random' numbers twice in one session.
358 function sq_mt_randomize()
359 {
360 global $REMOTE_PORT, $REMOTE_ADDR, $UNIQUE_ID;
361 static $randomized;
362
363 if ($randomized)
364 return;
365
366 // Global
367 sq_mt_seed((int)((double) microtime() * 1000000));
368 sq_mt_seed(md5($REMOTE_PORT . $REMOTE_ADDR . getmypid()));
369
370 // getrusage
371 if (function_exists("getrusage")) {
372 $dat = getrusage();
373 sq_mt_seed(md5($dat["ru_nswap"] . $dat["ru_majflt"] .
374 $dat["ru_utime.tv_sec"] . $dat["ru_utime.tv_usec"]));
375 }
376
377 // Apache-specific
378 sq_mt_seed(md5($UNIQUE_ID));
379
380 $randomized = 1;
381 }
382
383 function OneTimePadCreate ($length=100) {
384 sq_mt_randomize();
385
386 for ($i = 0; $i < $length; $i++) {
387 $pad .= chr(mt_rand(0,255));
388 }
389
390 return $pad;
391 }
392
393 // Check if we have a required PHP-version. Return TRUE if we do,
394 // or FALSE if we don't.
395 // To check for 4.0.1, use sqCheckPHPVersion(4,0,1)
396 // To check for 4.0b3, use sqCheckPHPVersion(4,0,-3)
397 // Does not handle betas like 4.0.1b1 or development versions
398 function sqCheckPHPVersion($major, $minor, $release) {
399
400 $ver = phpversion();
401 eregi("^([0-9]+)\.([0-9]+)(.*)", $ver, $regs);
402
403 // Parse the version string
404 $vmajor = strval($regs[1]);
405 $vminor = strval($regs[2]);
406 $vrel = $regs[3];
407 if($vrel[0] == ".")
408 $vrel = strval(substr($vrel, 1));
409 if($vrel[0] == "b" || $vrel[0] == "B")
410 $vrel = - strval(substr($vrel, 1));
411 if($vrel[0] == "r" || $vrel[0] == "R")
412 $vrel = - strval(substr($vrel, 2))/10;
413
414 // Compare major version
415 if($vmajor < $major) return false;
416 if($vmajor > $major) return true;
417
418 // Major is the same. Compare minor
419 if($vminor < $minor) return false;
420 if($vminor > $minor) return true;
421
422 // Major and minor is the same as the required one.
423 // Compare release
424 if($vrel >= 0 && $release >= 0) { // Neither are beta
425 if($vrel < $release) return false;
426 } else if($vrel >= 0 && $release < 0){ // This is not beta, required is beta
427 return true;
428 } else if($vrel < 0 && $release >= 0){ // This is beta, require not beta
429 return false;
430 } else { // Both are beta
431 if($vrel > $release) return false;
432 }
433
434 return true;
435 }
436
437 /* Returns a string showing the size of the message/attachment */
438 function show_readable_size($bytes)
439 {
440 $bytes /= 1024;
441 $type = 'k';
442
443 if ($bytes / 1024 > 1)
444 {
445 $bytes /= 1024;
446 $type = 'm';
447 }
448
449 if ($bytes < 10)
450 {
451 $bytes *= 10;
452 settype($bytes, "integer");
453 $bytes /= 10;
454 }
455 else
456 settype($bytes, "integer");
457
458 return $bytes . '<small>&nbsp;' . $type . '</small>';
459 }
460
461 /* Generates a random string from the caracter set you pass in
462 *
463 * Flags:
464 * 1 = add lowercase a-z to $chars
465 * 2 = add uppercase A-Z to $chars
466 * 4 = add numbers 0-9 to $chars
467 */
468
469 function GenerateRandomString($size, $chars, $flags = 0)
470 {
471 if ($flags & 0x1)
472 $chars .= 'abcdefghijklmnopqrstuvwxyz';
473 if ($flags & 0x2)
474 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
475 if ($flags & 0x4)
476 $chars .= '0123456789';
477
478 if ($size < 1 || strlen($chars) < 1)
479 return "";
480
481 sq_mt_randomize(); // Initialize the random number generator
482
483 while (strlen($String) < $size) {
484 $String .= $chars[mt_rand(0, strlen($chars))];
485 }
486
487 return $String;
488 }
489
490 ?>