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