4 * Copyright (c) 1999-2001 The Squirrelmail Development Team
5 * Licensed under the GNU GPL. For full terms see the file COPYING.
7 * This code provides various string manipulation functions that are
8 * used by the rest of the Squirrelmail code.
14 * SquirrelMail version number -- DO NOT CHANGE
17 $version = '1.2.0 [cvs]';
20 * Count the number of occurances of $needle are in $haystack.
21 * $needle can be a character or string, and need not occur in $haystack
23 function countCharInString($haystack, $needle) {
24 if ($needle == '') return 0;
25 return count(explode($needle, $haystack));
29 * Read from the back of $haystack until $needle is found, or the begining
30 * of the $haystack is reached. $needle is a single character
32 function readShortMailboxName($haystack, $needle) {
33 if ($needle == '') return $haystack;
34 $parts = explode($needle, $haystack);
35 $elem = array_pop($parts);
36 while ($elem == '' && count($parts))
38 $elem = array_pop($parts);
44 * Read from the back of $haystack until $needle is found, or the begining
45 * of the $haystack is reached. $needle is a single character
47 function readMailboxParent($haystack, $needle) {
48 if ($needle == '') return '';
49 $parts = explode($needle, $haystack);
50 $elem = array_pop($parts);
51 while ($elem == '' && count($parts))
53 $elem = array_pop($parts);
55 return join($needle, $parts);
59 * Searches for the next position in a string minus white space.
61 function next_pos_minus_white ($haystack, $pos) {
62 while (substr($haystack, $pos, 1) == ' ' ||
63 substr($haystack, $pos, 1) == "\t" ||
64 substr($haystack, $pos, 1) == "\n" ||
65 substr($haystack, $pos, 1) == "\r") {
66 if ($pos >= strlen($haystack))
74 * Wraps text at $wrap characters
76 * Has a problem with special HTML characters, so call this before
77 * you do character translation.
79 * Specifically, ' comes up as 5 characters instead of 1.
80 * This should not add newlines to the end of lines.
82 function sqWordWrap(&$line, $wrap) {
83 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
84 $beginning_spaces = $regs[1];
85 if (isset($regs[2])) {
86 $words = explode(' ', $regs[2]);
92 $line = $beginning_spaces;
94 while ($i < count($words)) {
95 // Force one word to be on a line (minimum)
97 $line_len = strlen($beginning_spaces) +
strlen($words[$i]) +
2;
98 if (isset($words[$i +
1]))
99 $line_len +
= strlen($words[$i +
1]);
102 // Add more words (as long as they fit)
103 while ($line_len < $wrap && $i < count($words)) {
104 $line .= ' ' . $words[$i];
106 if (isset($words[$i]))
107 $line_len +
= strlen($words[$i]) +
1;
112 // Skip spaces if they are the first thing on a continued line
113 while (!isset($words[$i]) && $i < count($words)) {
117 // Go to the next line if we have more to process
118 if ($i < count($words)) {
119 $line .= "\n" . $beginning_spaces;
126 * Does the opposite of sqWordWrap()
128 function sqUnWordWrap(&$body) {
129 $lines = explode("\n", $body);
131 $PreviousSpaces = "";
132 for ($i = 0; $i < count($lines); $i ++
) {
133 ereg("^([\t >]*)([^\t >].*)?$", $lines[$i], $regs);
134 $CurrentSpaces = $regs[1];
135 if (isset($regs[2])) {
136 $CurrentRest = $regs[2];
140 $PreviousSpaces = $CurrentSpaces;
142 } else if (($PreviousSpaces == $CurrentSpaces) // Do the beginnings match
143 && (strlen($lines[$i - 1]) > 65) // Over 65 characters long
144 && strlen($CurrentRest)) { // and there's a line to continue with
145 $body .= ' ' . $CurrentRest;
147 $body .= "\n" . $lines[$i];
148 $PreviousSpaces = $CurrentSpaces;
156 * Returns an array of email addresses.
157 * Be cautious of "user@host.com"
159 function parseAddrs($text) {
160 if (trim($text) == "")
162 $text = str_replace(' ', '', $text);
163 $text = ereg_replace('"[^"]*"', '', $text);
164 $text = ereg_replace('\\([^\\)]*\\)', '', $text);
165 $text = str_replace(',', ';', $text);
166 $array = explode(';', $text);
167 for ($i = 0; $i < count ($array); $i++
) {
168 $array[$i] = eregi_replace ("^.*[<]", '', $array[$i]);
169 $array[$i] = eregi_replace ("[>].*$", '', $array[$i]);
175 * Returns a line of comma separated email addresses from an array.
177 function getLineOfAddrs($array) {
178 if (is_array($array)) {
179 $to_line = implode(', ', $array);
180 $to_line = ereg_replace(', (, )+', ', ', $to_line);
181 $to_line = trim(ereg_replace('^, ', '', $to_line));
182 if( substr( $to_line, -1 ) == ',' )
183 $to_line = substr( $to_line, 0, -1 );
191 function translateText(&$body, $wrap_at, $charset) {
192 global $where, $what; // from searching
193 global $color; // color theme
195 require_once('../functions/url_parser.php');
197 $body_ary = explode("\n", $body);
199 for ($i=0; $i < count($body_ary); $i++
) {
200 $line = $body_ary[$i];
201 if (strlen($line) - 2 >= $wrap_at) {
202 sqWordWrap($line, $wrap_at);
204 $line = charset_decode($charset, $line);
205 $line = str_replace("\t", ' ', $line);
212 if ($line[$pos] == ' ') {
214 } else if (strpos($line, '>', $pos) === $pos) {
223 if (! isset($color[14])) {
224 $color[14] = '#FF0000';
226 $line = '<FONT COLOR="' . $color[14] . '">' . $line . '</FONT>';
228 if (! isset($color[13])) {
229 $color[13] = '#800000';
231 $line = '<FONT COLOR="' . $color[13] . '">' . $line . '</FONT>';
234 $body_ary[$i] = $line;
236 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
239 function find_mailbox_name ($mailbox) {
240 if (ereg(" *\"([^\r\n\"]*)\"[ \r\n]*$", $mailbox, $regs))
242 ereg(" *([^ \r\n\"]*)[ \r\n]*$",$mailbox,$regs);
248 * This determines the location to forward to relative to your server.
249 * If this doesnt work correctly for you (although it should), you can
250 * remove all this code except the last two lines, and change the header()
251 * function to look something like this, customized to the location of
252 * SquirrelMail on your server:
254 * http://www.myhost.com/squirrelmail/src/login.php
256 function get_location () {
258 global $PHP_SELF, $SERVER_NAME, $HTTP_HOST, $SERVER_PORT,
262 $path = substr($PHP_SELF, 0, strrpos($PHP_SELF, '/'));
264 /* Check if this is a HTTPS or regular HTTP request. */
268 * If you have 'SSLOptions +StdEnvVars' in your apache config
269 * OR if you have HTTPS in your HTTP_SERVER_VARS
270 * OR if you are on port 443
272 $getEnvVar = getenv('HTTPS');
273 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
274 (isset($HTTP_SERVER_VARS['HTTPS'])) ||
275 (isset($HTTP_SERVER_VARS['SERVER_PORT']) &&
276 $HTTP_SERVER_VARS['SERVER_PORT'] == 443)) {
280 // Get the hostname from the Host header or server config.
282 if (isset($HTTP_HOST) && !empty($HTTP_HOST)) {
284 } else if (isset($SERVER_NAME) && !empty($SERVER_NAME)) {
285 $host = $SERVER_NAME;
289 if (! strstr($host, ':')) {
290 if (isset($SERVER_PORT)) {
291 if (($SERVER_PORT != 80 && $proto == 'http://')
292 ||
($SERVER_PORT != 443 && $proto == 'https://')) {
293 $port = sprintf(':%d', $SERVER_PORT);
298 /* Fallback is to omit the server name and use a relative */
299 /* URI, although this is not RFC 2616 compliant. */
300 return ($host ?
$proto . $host . $port . $path : $path);
305 * These functions are used to encrypt the passowrd before it is
306 * stored in a cookie.
308 function OneTimePadEncrypt ($string, $epad) {
309 $pad = base64_decode($epad);
311 for ($i = 0; $i < strlen ($string); $i++
) {
312 $encrypted .= chr (ord($string[$i]) ^
ord($pad[$i]));
315 return base64_encode($encrypted);
318 function OneTimePadDecrypt ($string, $epad) {
319 $pad = base64_decode($epad);
320 $encrypted = base64_decode ($string);
322 for ($i = 0; $i < strlen ($encrypted); $i++
) {
323 $decrypted .= chr (ord($encrypted[$i]) ^
ord($pad[$i]));
331 * Randomize the mt_rand() function. Toss this in strings or integers
332 * and it will seed the generator appropriately. With strings, it is
333 * better to get them long. Use md5() to lengthen smaller strings.
335 function sq_mt_seed($Val) {
336 // if mt_getrandmax() does not return a 2^n - 1 number,
337 // this might not work well. This uses $Max as a bitmask.
338 $Max = mt_getrandmax();
340 if (! is_int($Val)) {
341 if (function_exists('crc32')) {
348 $HighBit = $Max ^
$Mask;
349 while ($Pos < strlen($Str)) {
350 if ($Val & $HighBit) {
351 $Val = (($Val & $Mask) << 1) +
1;
353 $Val = ($Val & $Mask) << 1;
369 mt_srand(($Val ^
mt_rand(0, $Max)) & $Max);
374 * This function initializes the random number generator fairly well.
375 * It also only initializes it once, so you don't accidentally get
376 * the same 'random' numbers twice in one session.
378 function sq_mt_randomize() {
379 global $REMOTE_PORT, $REMOTE_ADDR, $UNIQUE_ID;
387 sq_mt_seed((int)((double) microtime() * 1000000));
388 sq_mt_seed(md5($REMOTE_PORT . $REMOTE_ADDR . getmypid()));
391 if (function_exists('getrusage')) {
392 // Avoid warnings with Win32
394 if (isset($dat) && is_array($dat)) {
396 foreach ($dat as $k => $v)
400 sq_mt_seed(md5($Str));
405 sq_mt_seed(md5($UNIQUE_ID));
410 function OneTimePadCreate ($length=100) {
414 for ($i = 0; $i < $length; $i++
) {
415 $pad .= chr(mt_rand(0,255));
418 return base64_encode($pad);
422 * Check if we have a required PHP-version. Return TRUE if we do,
423 * or FALSE if we don't.
425 * To check for 4.0.1, use sqCheckPHPVersion(4,0,1)
426 * To check for 4.0b3, use sqCheckPHPVersion(4,0,-3)
428 * Does not handle betas like 4.0.1b1 or development versions
430 function sqCheckPHPVersion($major, $minor, $release) {
433 eregi('^([0-9]+)\\.([0-9]+)(.*)', $ver, $regs);
435 /* Parse the version string. */
436 $vmajor = strval($regs[1]);
437 $vminor = strval($regs[2]);
439 if($vrel[0] == ".") {
440 $vrel = strval(substr($vrel, 1));
442 if($vrel[0] == 'b' ||
$vrel[0] == 'B') {
443 $vrel = - strval(substr($vrel, 1));
445 if($vrel[0] == 'r' ||
$vrel[0] == 'R') {
446 $vrel = - strval(substr($vrel, 2))/10;
449 /* Compare major version. */
450 if ($vmajor < $major) { return false; }
451 if ($vmajor > $major) { return true; }
453 /* Major is the same. Compare minor. */
454 if ($vminor < $minor) { return false; }
455 if ($vminor > $minor) { return true; }
457 /* Major and minor is the same as the required one. Compare release */
458 if ($vrel >= 0 && $release >= 0) { // Neither are beta
459 if($vrel < $release) return false;
460 } else if($vrel >= 0 && $release < 0) { // This is not beta, required is beta
462 } else if($vrel < 0 && $release >= 0){ // This is beta, require not beta
464 } else { // Both are beta
465 if($vrel > $release) return false;
472 * Returns a string showing the size of the message/attachment.
474 function show_readable_size($bytes) {
478 if ($bytes / 1024 > 1) {
485 settype($bytes, 'integer');
488 settype($bytes, 'integer');
491 return $bytes . '<small> ' . $type . '</small>';
495 * Generates a random string from the caracter set you pass in
498 * 1 = add lowercase a-z to $chars
499 * 2 = add uppercase A-Z to $chars
500 * 4 = add numbers 0-9 to $chars
503 function GenerateRandomString($size, $chars, $flags = 0) {
505 $chars .= 'abcdefghijklmnopqrstuvwxyz';
508 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
511 $chars .= '0123456789';
514 if (($size < 1) ||
(strlen($chars) < 1)) {
518 sq_mt_randomize(); // Initialize the random number generator
521 while (strlen($String) < $size) {
522 $String .= $chars[mt_rand(0, strlen($chars))];
528 function quoteIMAP($str) {
529 return ereg_replace('(["\\])', '\\\\1', $str);
533 * Trims every element in the array
535 function TrimArray(&$array) {
536 foreach ($array as $k => $v) {
539 foreach ($
$k as $k2 => $v2) {
540 $
$k[$k2] = substr($v2, 1);
546 /* Re-assign back to array. */
552 * Removes slashes from every element in the array
554 function RemoveSlashes(&$array) {
555 foreach ($array as $k => $v) {
558 foreach ($
$k as $k2 => $v2) {
559 $newArray[stripslashes($k2)] = stripslashes($v2);
563 $
$k = stripslashes($v);
566 /* Re-assign back to the array. */