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.
13 if (defined('strings_php')) { return; }
14 define('strings_php', true);
17 * SquirrelMail version number -- DO NOT CHANGE
20 $version = '1.2.0 [cvs]';
23 * Count the number of occurances of $needle are in $haystack.
24 * $needle can be a character or string, and need not occur in $haystack
26 function countCharInString($haystack, $needle) {
27 if ($needle == '') return 0;
28 return count(explode($needle, $haystack));
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
35 function readShortMailboxName($haystack, $needle) {
36 if ($needle == '') return $haystack;
37 $parts = explode($needle, $haystack);
38 $elem = array_pop($parts);
39 while ($elem == '' && count($parts))
41 $elem = array_pop($parts);
47 * Read from the back of $haystack until $needle is found, or the begining
48 * of the $haystack is reached. $needle is a single character
50 function readMailboxParent($haystack, $needle) {
51 if ($needle == '') return '';
52 $parts = explode($needle, $haystack);
53 $elem = array_pop($parts);
54 while ($elem == '' && count($parts))
56 $elem = array_pop($parts);
58 return join($needle, $parts);
62 * Searches for the next position in a string minus white space.
64 function next_pos_minus_white ($haystack, $pos) {
65 while (substr($haystack, $pos, 1) == ' ' ||
66 substr($haystack, $pos, 1) == "\t" ||
67 substr($haystack, $pos, 1) == "\n" ||
68 substr($haystack, $pos, 1) == "\r") {
69 if ($pos >= strlen($haystack))
77 * Wraps text at $wrap characters
79 * Has a problem with special HTML characters, so call this before
80 * you do character translation.
82 * Specifically, ' comes up as 5 characters instead of 1.
83 * This should not add newlines to the end of lines.
85 function sqWordWrap(&$line, $wrap) {
86 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
87 $beginning_spaces = $regs[1];
88 if (isset($regs[2])) {
89 $words = explode(' ', $regs[2]);
95 $line = $beginning_spaces;
97 while ($i < count($words)) {
98 // Force one word to be on a line (minimum)
100 $line_len = strlen($beginning_spaces) +
strlen($words[$i]) +
2;
101 if (isset($words[$i +
1]))
102 $line_len +
= strlen($words[$i +
1]);
105 // Add more words (as long as they fit)
106 while ($line_len < $wrap && $i < count($words)) {
107 $line .= ' ' . $words[$i];
109 if (isset($words[$i]))
110 $line_len +
= strlen($words[$i]) +
1;
115 // Skip spaces if they are the first thing on a continued line
116 while (!isset($words[$i]) && $i < count($words)) {
120 // Go to the next line if we have more to process
121 if ($i < count($words)) {
122 $line .= "\n" . $beginning_spaces;
129 * Does the opposite of sqWordWrap()
131 function sqUnWordWrap(&$body) {
132 $lines = explode("\n", $body);
134 $PreviousSpaces = "";
135 for ($i = 0; $i < count($lines); $i ++
) {
136 ereg("^([\t >]*)([^\t >].*)?$", $lines[$i], $regs);
137 $CurrentSpaces = $regs[1];
138 if (isset($regs[2])) {
139 $CurrentRest = $regs[2];
143 $PreviousSpaces = $CurrentSpaces;
145 } else if (($PreviousSpaces == $CurrentSpaces) // Do the beginnings match
146 && (strlen($lines[$i - 1]) > 65) // Over 65 characters long
147 && strlen($CurrentRest)) { // and there's a line to continue with
148 $body .= ' ' . $CurrentRest;
150 $body .= "\n" . $lines[$i];
151 $PreviousSpaces = $CurrentSpaces;
159 * Returns an array of email addresses.
160 * Be cautious of "user@host.com"
162 function parseAddrs($text) {
163 if (trim($text) == "")
165 $text = str_replace(' ', '', $text);
166 $text = ereg_replace('"[^"]*"', '', $text);
167 $text = ereg_replace('\\([^\\)]*\\)', '', $text);
168 $text = str_replace(',', ';', $text);
169 $array = explode(';', $text);
170 for ($i = 0; $i < count ($array); $i++
) {
171 $array[$i] = eregi_replace ("^.*[<]", '', $array[$i]);
172 $array[$i] = eregi_replace ("[>].*$", '', $array[$i]);
178 * Returns a line of comma separated email addresses from an array.
180 function getLineOfAddrs($array) {
181 if (is_array($array)) {
182 $to_line = implode(', ', $array);
183 $to_line = ereg_replace(', (, )+', ', ', $to_line);
184 $to_line = trim(ereg_replace('^, ', '', $to_line));
185 if( substr( $to_line, -1 ) == ',' )
186 $to_line = substr( $to_line, 0, -1 );
194 function translateText(&$body, $wrap_at, $charset) {
195 global $where, $what; // from searching
196 global $color; // color theme
198 require_once('../functions/url_parser.php');
200 $body_ary = explode("\n", $body);
202 for ($i=0; $i < count($body_ary); $i++
) {
203 $line = $body_ary[$i];
204 if (strlen($line) - 2 >= $wrap_at) {
205 sqWordWrap($line, $wrap_at);
207 $line = charset_decode($charset, $line);
208 $line = str_replace("\t", ' ', $line);
215 if ($line[$pos] == ' ') {
217 } else if (strpos($line, '>', $pos) === $pos) {
226 if (! isset($color[14])) {
227 $color[14] = '#FF0000';
229 $line = '<FONT COLOR="' . $color[14] . '">' . $line . '</FONT>';
231 if (! isset($color[13])) {
232 $color[13] = '#800000';
234 $line = '<FONT COLOR="' . $color[13] . '">' . $line . '</FONT>';
237 $body_ary[$i] = $line;
239 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
242 function find_mailbox_name ($mailbox) {
243 if (ereg(" *\"([^\r\n\"]*)\"[ \r\n]*$", $mailbox, $regs))
245 ereg(" *([^ \r\n\"]*)[ \r\n]*$",$mailbox,$regs);
251 * This determines the location to forward to relative to your server.
252 * If this doesnt work correctly for you (although it should), you can
253 * remove all this code except the last two lines, and change the header()
254 * function to look something like this, customized to the location of
255 * SquirrelMail on your server:
257 * http://www.myhost.com/squirrelmail/src/login.php
259 function get_location () {
261 global $PHP_SELF, $SERVER_NAME, $HTTP_HOST, $SERVER_PORT,
265 $path = substr($PHP_SELF, 0, strrpos($PHP_SELF, '/'));
267 /* Check if this is a HTTPS or regular HTTP request. */
271 * If you have 'SSLOptions +StdEnvVars' in your apache config
272 * OR if you have HTTPS in your HTTP_SERVER_VARS
273 * OR if you are on port 443
275 $getEnvVar = getenv('HTTPS');
276 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
277 (isset($HTTP_SERVER_VARS['HTTPS'])) ||
278 (isset($HTTP_SERVER_VARS['SERVER_PORT']) &&
279 $HTTP_SERVER_VARS['SERVER_PORT'] == 443)) {
283 // Get the hostname from the Host header or server config.
285 if (isset($HTTP_HOST) && !empty($HTTP_HOST)) {
287 } else if (isset($SERVER_NAME) && !empty($SERVER_NAME)) {
288 $host = $SERVER_NAME;
292 if (! strstr($host, ':')) {
293 if (isset($SERVER_PORT)) {
294 if (($SERVER_PORT != 80 && $proto == 'http://')
295 ||
($SERVER_PORT != 443 && $proto == 'https://')) {
296 $port = sprintf(':%d', $SERVER_PORT);
301 /* Fallback is to omit the server name and use a relative */
302 /* URI, although this is not RFC 2616 compliant. */
303 return ($host ?
$proto . $host . $port . $path : $path);
308 * These functions are used to encrypt the passowrd before it is
309 * stored in a cookie.
311 function OneTimePadEncrypt ($string, $epad) {
312 $pad = base64_decode($epad);
314 for ($i = 0; $i < strlen ($string); $i++
) {
315 $encrypted .= chr (ord($string[$i]) ^
ord($pad[$i]));
318 return base64_encode($encrypted);
321 function OneTimePadDecrypt ($string, $epad) {
322 $pad = base64_decode($epad);
323 $encrypted = base64_decode ($string);
325 for ($i = 0; $i < strlen ($encrypted); $i++
) {
326 $decrypted .= chr (ord($encrypted[$i]) ^
ord($pad[$i]));
334 * Randomize the mt_rand() function. Toss this in strings or integers
335 * and it will seed the generator appropriately. With strings, it is
336 * better to get them long. Use md5() to lengthen smaller strings.
338 function sq_mt_seed($Val) {
339 // if mt_getrandmax() does not return a 2^n - 1 number,
340 // this might not work well. This uses $Max as a bitmask.
341 $Max = mt_getrandmax();
343 if (! is_int($Val)) {
344 if (function_exists('crc32')) {
351 $HighBit = $Max ^
$Mask;
352 while ($Pos < strlen($Str)) {
353 if ($Val & $HighBit) {
354 $Val = (($Val & $Mask) << 1) +
1;
356 $Val = ($Val & $Mask) << 1;
372 mt_srand(($Val ^
mt_rand(0, $Max)) & $Max);
377 * This function initializes the random number generator fairly well.
378 * It also only initializes it once, so you don't accidentally get
379 * the same 'random' numbers twice in one session.
381 function sq_mt_randomize() {
382 global $REMOTE_PORT, $REMOTE_ADDR, $UNIQUE_ID;
390 sq_mt_seed((int)((double) microtime() * 1000000));
391 sq_mt_seed(md5($REMOTE_PORT . $REMOTE_ADDR . getmypid()));
394 if (function_exists('getrusage')) {
395 // Avoid warnings with Win32
397 if (isset($dat) && is_array($dat)) {
399 foreach ($dat as $k => $v)
403 sq_mt_seed(md5($Str));
408 sq_mt_seed(md5($UNIQUE_ID));
413 function OneTimePadCreate ($length=100) {
417 for ($i = 0; $i < $length; $i++
) {
418 $pad .= chr(mt_rand(0,255));
421 return base64_encode($pad);
425 * Check if we have a required PHP-version. Return TRUE if we do,
426 * or FALSE if we don't.
428 * To check for 4.0.1, use sqCheckPHPVersion(4,0,1)
429 * To check for 4.0b3, use sqCheckPHPVersion(4,0,-3)
431 * Does not handle betas like 4.0.1b1 or development versions
433 function sqCheckPHPVersion($major, $minor, $release) {
436 eregi('^([0-9]+)\\.([0-9]+)(.*)', $ver, $regs);
438 /* Parse the version string. */
439 $vmajor = strval($regs[1]);
440 $vminor = strval($regs[2]);
442 if($vrel[0] == ".") {
443 $vrel = strval(substr($vrel, 1));
445 if($vrel[0] == 'b' ||
$vrel[0] == 'B') {
446 $vrel = - strval(substr($vrel, 1));
448 if($vrel[0] == 'r' ||
$vrel[0] == 'R') {
449 $vrel = - strval(substr($vrel, 2))/10;
452 /* Compare major version. */
453 if ($vmajor < $major) { return false; }
454 if ($vmajor > $major) { return true; }
456 /* Major is the same. Compare minor. */
457 if ($vminor < $minor) { return false; }
458 if ($vminor > $minor) { return true; }
460 /* Major and minor is the same as the required one. Compare release */
461 if ($vrel >= 0 && $release >= 0) { // Neither are beta
462 if($vrel < $release) return false;
463 } else if($vrel >= 0 && $release < 0) { // This is not beta, required is beta
465 } else if($vrel < 0 && $release >= 0){ // This is beta, require not beta
467 } else { // Both are beta
468 if($vrel > $release) return false;
475 * Returns a string showing the size of the message/attachment.
477 function show_readable_size($bytes) {
481 if ($bytes / 1024 > 1) {
488 settype($bytes, 'integer');
491 settype($bytes, 'integer');
494 return $bytes . '<small> ' . $type . '</small>';
498 * Generates a random string from the caracter set you pass in
501 * 1 = add lowercase a-z to $chars
502 * 2 = add uppercase A-Z to $chars
503 * 4 = add numbers 0-9 to $chars
506 function GenerateRandomString($size, $chars, $flags = 0) {
508 $chars .= 'abcdefghijklmnopqrstuvwxyz';
511 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
514 $chars .= '0123456789';
517 if (($size < 1) ||
(strlen($chars) < 1)) {
521 sq_mt_randomize(); // Initialize the random number generator
524 while (strlen($String) < $size) {
525 $String .= $chars[mt_rand(0, strlen($chars))];
531 function quoteIMAP($str) {
532 return ereg_replace('(["\\])', '\\\\1', $str);
536 * Trims every element in the array
538 function TrimArray(&$array) {
539 foreach ($array as $k => $v) {
542 foreach ($
$k as $k2 => $v2) {
543 $
$k[$k2] = substr($v2, 1);
549 /* Re-assign back to array. */
555 * Removes slashes from every element in the array
557 function RemoveSlashes(&$array) {
558 foreach ($array as $k => $v) {
561 foreach ($
$k as $k2 => $v2) {
562 $newArray[stripslashes($k2)] = stripslashes($v2);
566 $
$k = stripslashes($v);
569 /* Re-assign back to the array. */