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