6 * Copyright (c) 1999-2001 The Squirrelmail Development Team
7 * Licensed under the GNU GPL. For full terms see the file COPYING.
9 * This code provides various string manipulation functions that are
10 * used by the rest of the Squirrelmail code.
16 * SquirrelMail version number -- DO NOT CHANGE
19 $version = '1.2.0 [cvs]';
22 * Count the number of occurances of $needle are in $haystack.
23 * $needle can be a character or string, and need not occur in $haystack
25 function countCharInString($haystack, $needle) {
26 if ($needle == '') return 0;
27 return count(explode($needle, $haystack));
31 * Read from the back of $haystack until $needle is found, or the begining
32 * of the $haystack is reached. $needle is a single character
34 function readShortMailboxName($haystack, $needle) {
35 if ($needle == '') return $haystack;
36 $parts = explode($needle, $haystack);
37 $elem = array_pop($parts);
38 while ($elem == '' && count($parts))
40 $elem = array_pop($parts);
46 * Read from the back of $haystack until $needle is found, or the begining
47 * of the $haystack is reached. $needle is a single character
49 function readMailboxParent($haystack, $needle) {
50 if ($needle == '') return '';
51 $parts = explode($needle, $haystack);
52 $elem = array_pop($parts);
53 while ($elem == '' && count($parts))
55 $elem = array_pop($parts);
57 return join($needle, $parts);
61 * Searches for the next position in a string minus white space.
63 function next_pos_minus_white ($haystack, $pos) {
64 while (substr($haystack, $pos, 1) == ' ' ||
65 substr($haystack, $pos, 1) == "\t" ||
66 substr($haystack, $pos, 1) == "\n" ||
67 substr($haystack, $pos, 1) == "\r") {
68 if ($pos >= strlen($haystack))
76 * Wraps text at $wrap characters
78 * Has a problem with special HTML characters, so call this before
79 * you do character translation.
81 * Specifically, ' comes up as 5 characters instead of 1.
82 * This should not add newlines to the end of lines.
84 function sqWordWrap(&$line, $wrap) {
85 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
86 $beginning_spaces = $regs[1];
87 if (isset($regs[2])) {
88 $words = explode(' ', $regs[2]);
94 $line = $beginning_spaces;
96 while ($i < count($words)) {
97 // Force one word to be on a line (minimum)
99 $line_len = strlen($beginning_spaces) +
strlen($words[$i]) +
2;
100 if (isset($words[$i +
1]))
101 $line_len +
= strlen($words[$i +
1]);
104 // Add more words (as long as they fit)
105 while ($line_len < $wrap && $i < count($words)) {
106 $line .= ' ' . $words[$i];
108 if (isset($words[$i]))
109 $line_len +
= strlen($words[$i]) +
1;
114 // Skip spaces if they are the first thing on a continued line
115 while (!isset($words[$i]) && $i < count($words)) {
119 // Go to the next line if we have more to process
120 if ($i < count($words)) {
121 $line .= "\n" . $beginning_spaces;
128 * Does the opposite of sqWordWrap()
130 function sqUnWordWrap(&$body) {
131 $lines = explode("\n", $body);
133 $PreviousSpaces = "";
134 for ($i = 0; $i < count($lines); $i ++
) {
135 ereg("^([\t >]*)([^\t >].*)?$", $lines[$i], $regs);
136 $CurrentSpaces = $regs[1];
137 if (isset($regs[2])) {
138 $CurrentRest = $regs[2];
142 $PreviousSpaces = $CurrentSpaces;
144 } else if (($PreviousSpaces == $CurrentSpaces) // Do the beginnings match
145 && (strlen($lines[$i - 1]) > 65) // Over 65 characters long
146 && strlen($CurrentRest)) { // and there's a line to continue with
147 $body .= ' ' . $CurrentRest;
149 $body .= "\n" . $lines[$i];
150 $PreviousSpaces = $CurrentSpaces;
158 * Returns an array of email addresses.
159 * Be cautious of "user@host.com"
161 function parseAddrs($text) {
162 if (trim($text) == "")
164 $text = str_replace(' ', '', $text);
165 $text = ereg_replace('"[^"]*"', '', $text);
166 $text = ereg_replace('\\([^\\)]*\\)', '', $text);
167 $text = str_replace(',', ';', $text);
168 $array = explode(';', $text);
169 for ($i = 0; $i < count ($array); $i++
) {
170 $array[$i] = eregi_replace ("^.*[<]", '', $array[$i]);
171 $array[$i] = eregi_replace ("[>].*$", '', $array[$i]);
177 * Returns a line of comma separated email addresses from an array.
179 function getLineOfAddrs($array) {
180 if (is_array($array)) {
181 $to_line = implode(', ', $array);
182 $to_line = ereg_replace(', (, )+', ', ', $to_line);
183 $to_line = trim(ereg_replace('^, ', '', $to_line));
184 if( substr( $to_line, -1 ) == ',' )
185 $to_line = substr( $to_line, 0, -1 );
193 function translateText(&$body, $wrap_at, $charset) {
194 global $where, $what; // from searching
195 global $color; // color theme
197 require_once('../functions/url_parser.php');
199 $body_ary = explode("\n", $body);
201 for ($i=0; $i < count($body_ary); $i++
) {
202 $line = $body_ary[$i];
203 if (strlen($line) - 2 >= $wrap_at) {
204 sqWordWrap($line, $wrap_at);
206 $line = charset_decode($charset, $line);
207 $line = str_replace("\t", ' ', $line);
214 if ($line[$pos] == ' ') {
216 } else if (strpos($line, '>', $pos) === $pos) {
225 if (! isset($color[14])) {
226 $color[14] = '#FF0000';
228 $line = '<FONT COLOR="' . $color[14] . '">' . $line . '</FONT>';
230 if (! isset($color[13])) {
231 $color[13] = '#800000';
233 $line = '<FONT COLOR="' . $color[13] . '">' . $line . '</FONT>';
236 $body_ary[$i] = $line;
238 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
241 function find_mailbox_name ($mailbox) {
242 if (ereg(" *\"([^\r\n\"]*)\"[ \r\n]*$", $mailbox, $regs))
244 ereg(" *([^ \r\n\"]*)[ \r\n]*$",$mailbox,$regs);
250 * This determines the location to forward to relative to your server.
251 * If this doesnt work correctly for you (although it should), you can
252 * remove all this code except the last two lines, and change the header()
253 * function to look something like this, customized to the location of
254 * SquirrelMail on your server:
256 * http://www.myhost.com/squirrelmail/src/login.php
258 function get_location () {
260 global $PHP_SELF, $SERVER_NAME, $HTTP_HOST, $SERVER_PORT,
264 $path = substr($PHP_SELF, 0, strrpos($PHP_SELF, '/'));
266 /* Check if this is a HTTPS or regular HTTP request. */
270 * If you have 'SSLOptions +StdEnvVars' in your apache config
271 * OR if you have HTTPS in your HTTP_SERVER_VARS
272 * OR if you are on port 443
274 $getEnvVar = getenv('HTTPS');
275 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
276 (isset($HTTP_SERVER_VARS['HTTPS'])) ||
277 (isset($HTTP_SERVER_VARS['SERVER_PORT']) &&
278 $HTTP_SERVER_VARS['SERVER_PORT'] == 443)) {
282 // Get the hostname from the Host header or server config.
284 if (isset($HTTP_HOST) && !empty($HTTP_HOST)) {
286 } else if (isset($SERVER_NAME) && !empty($SERVER_NAME)) {
287 $host = $SERVER_NAME;
291 if (! strstr($host, ':')) {
292 if (isset($SERVER_PORT)) {
293 if (($SERVER_PORT != 80 && $proto == 'http://')
294 ||
($SERVER_PORT != 443 && $proto == 'https://')) {
295 $port = sprintf(':%d', $SERVER_PORT);
300 /* Fallback is to omit the server name and use a relative */
301 /* URI, although this is not RFC 2616 compliant. */
302 return ($host ?
$proto . $host . $port . $path : $path);
307 * These functions are used to encrypt the passowrd before it is
308 * stored in a cookie.
310 function OneTimePadEncrypt ($string, $epad) {
311 $pad = base64_decode($epad);
313 for ($i = 0; $i < strlen ($string); $i++
) {
314 $encrypted .= chr (ord($string[$i]) ^
ord($pad[$i]));
317 return base64_encode($encrypted);
320 function OneTimePadDecrypt ($string, $epad) {
321 $pad = base64_decode($epad);
322 $encrypted = base64_decode ($string);
324 for ($i = 0; $i < strlen ($encrypted); $i++
) {
325 $decrypted .= chr (ord($encrypted[$i]) ^
ord($pad[$i]));
333 * Randomize the mt_rand() function. Toss this in strings or integers
334 * and it will seed the generator appropriately. With strings, it is
335 * better to get them long. Use md5() to lengthen smaller strings.
337 function sq_mt_seed($Val) {
338 // if mt_getrandmax() does not return a 2^n - 1 number,
339 // this might not work well. This uses $Max as a bitmask.
340 $Max = mt_getrandmax();
342 if (! is_int($Val)) {
343 if (function_exists('crc32')) {
350 $HighBit = $Max ^
$Mask;
351 while ($Pos < strlen($Str)) {
352 if ($Val & $HighBit) {
353 $Val = (($Val & $Mask) << 1) +
1;
355 $Val = ($Val & $Mask) << 1;
371 mt_srand(($Val ^
mt_rand(0, $Max)) & $Max);
376 * This function initializes the random number generator fairly well.
377 * It also only initializes it once, so you don't accidentally get
378 * the same 'random' numbers twice in one session.
380 function sq_mt_randomize() {
381 global $REMOTE_PORT, $REMOTE_ADDR, $UNIQUE_ID;
389 sq_mt_seed((int)((double) microtime() * 1000000));
390 sq_mt_seed(md5($REMOTE_PORT . $REMOTE_ADDR . getmypid()));
393 if (function_exists('getrusage')) {
394 // Avoid warnings with Win32
396 if (isset($dat) && is_array($dat)) {
398 foreach ($dat as $k => $v)
402 sq_mt_seed(md5($Str));
407 sq_mt_seed(md5($UNIQUE_ID));
412 function OneTimePadCreate ($length=100) {
416 for ($i = 0; $i < $length; $i++
) {
417 $pad .= chr(mt_rand(0,255));
420 return base64_encode($pad);
424 * Check if we have a required PHP-version. Return TRUE if we do,
425 * or FALSE if we don't.
427 * To check for 4.0.1, use sqCheckPHPVersion(4,0,1)
428 * To check for 4.0b3, use sqCheckPHPVersion(4,0,-3)
430 * Does not handle betas like 4.0.1b1 or development versions
432 function sqCheckPHPVersion($major, $minor, $release) {
435 eregi('^([0-9]+)\\.([0-9]+)(.*)', $ver, $regs);
437 /* Parse the version string. */
438 $vmajor = strval($regs[1]);
439 $vminor = strval($regs[2]);
441 if($vrel[0] == ".") {
442 $vrel = strval(substr($vrel, 1));
444 if($vrel[0] == 'b' ||
$vrel[0] == 'B') {
445 $vrel = - strval(substr($vrel, 1));
447 if($vrel[0] == 'r' ||
$vrel[0] == 'R') {
448 $vrel = - strval(substr($vrel, 2))/10;
451 /* Compare major version. */
452 if ($vmajor < $major) { return false; }
453 if ($vmajor > $major) { return true; }
455 /* Major is the same. Compare minor. */
456 if ($vminor < $minor) { return false; }
457 if ($vminor > $minor) { return true; }
459 /* Major and minor is the same as the required one. Compare release */
460 if ($vrel >= 0 && $release >= 0) { // Neither are beta
461 if($vrel < $release) return false;
462 } else if($vrel >= 0 && $release < 0) { // This is not beta, required is beta
464 } else if($vrel < 0 && $release >= 0){ // This is beta, require not beta
466 } else { // Both are beta
467 if($vrel > $release) return false;
474 * Returns a string showing the size of the message/attachment.
476 function show_readable_size($bytes) {
480 if ($bytes / 1024 > 1) {
487 settype($bytes, 'integer');
490 settype($bytes, 'integer');
493 return $bytes . '<small> ' . $type . '</small>';
497 * Generates a random string from the caracter set you pass in
500 * 1 = add lowercase a-z to $chars
501 * 2 = add uppercase A-Z to $chars
502 * 4 = add numbers 0-9 to $chars
505 function GenerateRandomString($size, $chars, $flags = 0) {
507 $chars .= 'abcdefghijklmnopqrstuvwxyz';
510 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
513 $chars .= '0123456789';
516 if (($size < 1) ||
(strlen($chars) < 1)) {
520 sq_mt_randomize(); // Initialize the random number generator
523 while (strlen($String) < $size) {
524 $String .= $chars[mt_rand(0, strlen($chars))];
530 function quoteIMAP($str) {
531 return ereg_replace('(["\\])', '\\\\1', $str);
535 * Trims every element in the array
537 function TrimArray(&$array) {
538 foreach ($array as $k => $v) {
541 foreach ($
$k as $k2 => $v2) {
542 $
$k[$k2] = substr($v2, 1);
548 /* Re-assign back to array. */
554 * Removes slashes from every element in the array
556 function RemoveSlashes(&$array) {
557 foreach ($array as $k => $v) {
560 foreach ($
$k as $k2 => $v2) {
561 $newArray[stripslashes($k2)] = stripslashes($v2);
565 $
$k = stripslashes($v);
568 /* Re-assign back to the array. */