Correct changes of "" to ''.
[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 /*
213 $mailbox = trim($mailbox);
214 if (substr($mailbox, strlen($mailbox)-1, strlen($mailbox)) == '"') {
215 $mailbox = substr($mailbox, 0, strlen($mailbox) - 1);
216 $pos = strrpos ($mailbox, '"')+1;
217 $box = substr($mailbox, $pos);
218 } else {
219 $box = substr($mailbox, strrpos($mailbox, ' ')+1, strlen($mailbox));
220 }
221 return $box;
222 */
223
224 if (ereg(" *\"([^\r\n\"]*)\"[ \r\n]*$", $mailbox, $regs))
225 return $regs[1];
226 ereg(" *([^ \r\n\"]*)[ \r\n]*$",$mailbox,$regs);
227 return $regs[1];
228
229 }
230
231 function replace_spaces ($string) {
232 return str_replace(' ', '&nbsp;', $string);
233 }
234
235 function replace_escaped_spaces ($string) {
236 return str_replace('&nbsp;', ' ', $string);
237 }
238
239 function get_location () {
240 # This determines the location to forward to relative
241 # to your server. If this doesnt work correctly for
242 # you (although it should), you can remove all this
243 # code except the last two lines, and change the header()
244 # function to look something like this, customized to
245 # the location of SquirrelMail on your server:
246 #
247 # http://www.myhost.com/squirrelmail/src/login.php
248
249 global $PHP_SELF, $SERVER_NAME, $HTTPS, $HTTP_HOST, $SERVER_PORT;
250
251 // Get the path
252 $path = substr($PHP_SELF, 0, strrpos($PHP_SELF, '/'));
253
254 // Check if this is a HTTPS or regular HTTP request
255 $proto = 'http://';
256 if(isset($HTTPS) && !strcasecmp($HTTPS, 'on') ) {
257 $proto = 'https://';
258 }
259
260 // Get the hostname from the Host header or server config.
261 $host = '';
262 if (isset($HTTP_HOST) && !empty($HTTP_HOST))
263 {
264 $host = $HTTP_HOST;
265 }
266 else if (isset($SERVER_NAME) && !empty($SERVER_NAME))
267 {
268 $host = $SERVER_NAME;
269 }
270
271 $port = '';
272 if (! strstr($host, ':'))
273 {
274 if (isset($SERVER_PORT)) {
275 if (($SERVER_PORT != 80 && $proto == 'http://')
276 || ($SERVER_PORT != 443 && $proto == 'https://')) {
277 $port = sprintf(':%d', $SERVER_PORT);
278 }
279 }
280 }
281
282 if ($host)
283 return $proto . $host . $port . $path;
284
285 // Fallback is to omit the server name and use a relative URI,
286 // although this is not RFC 2616 compliant.
287 return $path;
288 }
289
290 function sqStripSlashes($string) {
291 if (get_magic_quotes_gpc()) {
292 $string = stripslashes($string);
293 }
294 return $string;
295 }
296
297
298 // These functions are used to encrypt the passowrd before it is
299 // stored in a cookie.
300 function OneTimePadEncrypt ($string, $epad) {
301 $pad = base64_decode($epad);
302 $encrypted = '';
303 for ($i = 0; $i < strlen ($string); $i++) {
304 $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
305 }
306
307 return base64_encode($encrypted);
308 }
309
310 function OneTimePadDecrypt ($string, $epad) {
311 $pad = base64_decode($epad);
312 $encrypted = base64_decode ($string);
313 $decrypted = '';
314 for ($i = 0; $i < strlen ($encrypted); $i++) {
315 $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
316 }
317
318 return $decrypted;
319 }
320
321
322 // Randomize the mt_rand() function. Toss this in strings or
323 // integers and it will seed the generator appropriately.
324 // With strings, it is better to get them long. Use md5() to
325 // lengthen smaller strings.
326 function sq_mt_seed($Val)
327 {
328 // if mt_getrandmax() does not return a 2^n - 1 number,
329 // this might not work well. This uses $Max as a bitmask.
330 $Max = mt_getrandmax();
331
332 if (! is_int($Val))
333 {
334 if (function_exists('crc32'))
335 {
336 $Val = crc32($Val);
337 }
338 else
339 {
340 $Str = $Val;
341 $Pos = 0;
342 $Val = 0;
343 $Mask = $Max / 2;
344 $HighBit = $Max ^ $Mask;
345 while ($Pos < strlen($Str))
346 {
347 if ($Val & $HighBit)
348 {
349 $Val = (($Val & $Mask) << 1) + 1;
350 }
351 else
352 {
353 $Val = ($Val & $Mask) << 1;
354 }
355 $Val ^= $Str[$Pos];
356 $Pos ++;
357 }
358 }
359 }
360
361 if ($Val < 0)
362 $Val *= -1;
363 if ($Val = 0)
364 return;
365
366 mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
367 }
368
369
370 // This function initializes the random number generator fairly well.
371 // It also only initializes it once, so you don't accidentally get
372 // the same 'random' numbers twice in one session.
373 function sq_mt_randomize()
374 {
375 global $REMOTE_PORT, $REMOTE_ADDR, $UNIQUE_ID;
376 static $randomized;
377
378 if ($randomized)
379 return;
380
381 // Global
382 sq_mt_seed((int)((double) microtime() * 1000000));
383 sq_mt_seed(md5($REMOTE_PORT . $REMOTE_ADDR . getmypid()));
384
385 // getrusage
386 if (function_exists('getrusage')) {
387 $dat = getrusage();
388 $Str = '';
389 foreach ($dat as $k => $v)
390 {
391 $Str .= "$k = $v\n";
392 }
393 sq_mt_seed(md5($Str));
394 }
395
396 // Apache-specific
397 sq_mt_seed(md5($UNIQUE_ID));
398
399 $randomized = 1;
400 }
401
402 function OneTimePadCreate ($length=100) {
403 sq_mt_randomize();
404
405 $pad = '';
406 for ($i = 0; $i < $length; $i++) {
407 $pad .= chr(mt_rand(0,255));
408 }
409
410 return base64_encode($pad);
411 }
412
413 // Check if we have a required PHP-version. Return TRUE if we do,
414 // or FALSE if we don't.
415 // To check for 4.0.1, use sqCheckPHPVersion(4,0,1)
416 // To check for 4.0b3, use sqCheckPHPVersion(4,0,-3)
417 // Does not handle betas like 4.0.1b1 or development versions
418 function sqCheckPHPVersion($major, $minor, $release) {
419
420 $ver = phpversion();
421 eregi("^([0-9]+)\.([0-9]+)(.*)", $ver, $regs);
422
423 // Parse the version string
424 $vmajor = strval($regs[1]);
425 $vminor = strval($regs[2]);
426 $vrel = $regs[3];
427 if($vrel[0] == ".")
428 $vrel = strval(substr($vrel, 1));
429 if($vrel[0] == 'b' || $vrel[0] == 'B')
430 $vrel = - strval(substr($vrel, 1));
431 if($vrel[0] == 'r' || $vrel[0] == 'R')
432 $vrel = - strval(substr($vrel, 2))/10;
433
434 // Compare major version
435 if($vmajor < $major) return false;
436 if($vmajor > $major) return true;
437
438 // Major is the same. Compare minor
439 if($vminor < $minor) return false;
440 if($vminor > $minor) return true;
441
442 // Major and minor is the same as the required one.
443 // Compare release
444 if($vrel >= 0 && $release >= 0) { // Neither are beta
445 if($vrel < $release) return false;
446 } else if($vrel >= 0 && $release < 0){ // This is not beta, required is beta
447 return true;
448 } else if($vrel < 0 && $release >= 0){ // This is beta, require not beta
449 return false;
450 } else { // Both are beta
451 if($vrel > $release) return false;
452 }
453
454 return true;
455 }
456
457 /* Returns a string showing the size of the message/attachment */
458 function show_readable_size($bytes)
459 {
460 $bytes /= 1024;
461 $type = 'k';
462
463 if ($bytes / 1024 > 1)
464 {
465 $bytes /= 1024;
466 $type = 'm';
467 }
468
469 if ($bytes < 10)
470 {
471 $bytes *= 10;
472 settype($bytes, 'integer');
473 $bytes /= 10;
474 }
475 else
476 settype($bytes, 'integer');
477
478 return $bytes . '<small>&nbsp;' . $type . '</small>';
479 }
480
481 /* Generates a random string from the caracter set you pass in
482 *
483 * Flags:
484 * 1 = add lowercase a-z to $chars
485 * 2 = add uppercase A-Z to $chars
486 * 4 = add numbers 0-9 to $chars
487 */
488
489 function GenerateRandomString($size, $chars, $flags = 0)
490 {
491 if ($flags & 0x1)
492 $chars .= 'abcdefghijklmnopqrstuvwxyz';
493 if ($flags & 0x2)
494 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
495 if ($flags & 0x4)
496 $chars .= '0123456789';
497
498 if ($size < 1 || strlen($chars) < 1)
499 return '';
500
501 sq_mt_randomize(); // Initialize the random number generator
502
503 $String = "";
504 while (strlen($String) < $size) {
505 $String .= $chars[mt_rand(0, strlen($chars))];
506 }
507
508 return $String;
509 }
510
511 ?>