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