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