6 * Copyright (c) 1999-2002 The SquirrelMail Project 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.6 [cvs]';
22 * If $haystack is a full mailbox name and $needle is the mailbox
23 * separator character, returns the last part of the mailbox name.
25 function readShortMailboxName($haystack, $needle) {
30 $parts = explode($needle, $haystack);
31 $elem = array_pop($parts);
32 while ($elem == '' && count($parts)) {
33 $elem = array_pop($parts);
40 * Wraps text at $wrap characters
42 * Has a problem with special HTML characters, so call this before
43 * you do character translation.
45 * Specifically, ' comes up as 5 characters instead of 1.
46 * This should not add newlines to the end of lines.
48 function sqWordWrap(&$line, $wrap) {
49 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
50 $beginning_spaces = $regs[1];
51 if (isset($regs[2])) {
52 $words = explode(' ', $regs[2]);
58 $line = $beginning_spaces;
60 while ($i < count($words)) {
61 /* Force one word to be on a line (minimum) */
63 $line_len = strlen($beginning_spaces) +
strlen($words[$i]) +
2;
64 if (isset($words[$i +
1]))
65 $line_len +
= strlen($words[$i +
1]);
68 /* Add more words (as long as they fit) */
69 while ($line_len < $wrap && $i < count($words)) {
70 $line .= ' ' . $words[$i];
72 if (isset($words[$i]))
73 $line_len +
= strlen($words[$i]) +
1;
78 /* Skip spaces if they are the first thing on a continued line */
79 while (!isset($words[$i]) && $i < count($words)) {
83 /* Go to the next line if we have more to process */
84 if ($i < count($words)) {
85 $line .= "\n" . $beginning_spaces;
92 * Does the opposite of sqWordWrap()
94 function sqUnWordWrap(&$body) {
95 $lines = explode("\n", $body);
98 for ($i = 0; $i < count($lines); $i ++
) {
99 ereg("^([\t >]*)([^\t >].*)?$", $lines[$i], $regs);
100 $CurrentSpaces = $regs[1];
101 if (isset($regs[2])) {
102 $CurrentRest = $regs[2];
106 $PreviousSpaces = $CurrentSpaces;
108 } else if (($PreviousSpaces == $CurrentSpaces) /* Do the beginnings match */
109 && (strlen($lines[$i - 1]) > 65) /* Over 65 characters long */
110 && strlen($CurrentRest)) { /* and there's a line to continue with */
111 $body .= ' ' . $CurrentRest;
113 $body .= "\n" . $lines[$i];
114 $PreviousSpaces = $CurrentSpaces;
122 * Returns an array of email addresses.
123 * Be cautious of "user@host.com"
125 function parseAddrs($text) {
126 if (trim($text) == '')
128 $text = str_replace(' ', '', $text);
129 $text = ereg_replace('"[^"]*"', '', $text);
130 $text = ereg_replace('\\([^\\)]*\\)', '', $text);
131 $text = str_replace(',', ';', $text);
132 $array = explode(';', $text);
133 for ($i = 0; $i < count ($array); $i++
) {
134 $array[$i] = eregi_replace ('^.*[<]', '', $array[$i]);
135 $array[$i] = eregi_replace ('[>].*$', '', $array[$i]);
141 * Returns a line of comma separated email addresses from an array.
143 function getLineOfAddrs($array) {
144 if (is_array($array)) {
145 $to_line = implode(', ', $array);
146 $to_line = ereg_replace(', (, )+', ', ', $to_line);
147 $to_line = trim(ereg_replace('^, ', '', $to_line));
148 if( substr( $to_line, -1 ) == ',' )
149 $to_line = substr( $to_line, 0, -1 );
157 function translateText(&$body, $wrap_at, $charset) {
158 global $where, $what; /* from searching */
159 global $color; /* color theme */
161 require_once('../functions/url_parser.php');
163 $body_ary = explode("\n", $body);
165 for ($i=0; $i < count($body_ary); $i++
) {
166 $line = $body_ary[$i];
167 if (strlen($line) - 2 >= $wrap_at) {
168 sqWordWrap($line, $wrap_at);
170 $line = charset_decode($charset, $line);
171 $line = str_replace("\t", ' ', $line);
177 $j = strlen( $line );
179 while ( $pos < $j ) {
180 if ($line[$pos] == ' ') {
182 } else if (strpos($line, '>', $pos) === $pos) {
191 if (! isset($color[14])) {
192 $color[14] = '#FF0000';
194 $line = '<FONT COLOR="' . $color[14] . '">' . $line . '</FONT>';
196 if (! isset($color[13])) {
197 $color[13] = '#800000';
199 $line = '<FONT COLOR="' . $color[13] . '">' . $line . '</FONT>';
202 $body_ary[$i] = $line;
204 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
207 function find_mailbox_name ($mailbox) {
208 if (ereg(" *\"([^\r\n\"]*)\"[ \r\n]*$", $mailbox, $regs))
210 ereg(" *([^ \r\n\"]*)[ \r\n]*$",$mailbox,$regs);
215 function php_self () {
216 global $PHP_SELF, $HTTP_SERVER_VARS;
218 if (isset($HTTP_SERVER_VARS['REQUEST_URI']) && !empty($HTTP_SERVER_VARS['REQUEST_URI']) ) {
219 return $HTTP_SERVER_VARS['REQUEST_URI'];
222 if (isset($PHP_SELF) && !empty($PHP_SELF)) {
224 } else if (isset($HTTP_SERVER_VARS['PHP_SELF']) &&
225 !empty($HTTP_SERVER_VARS['PHP_SELF'])) {
226 return $HTTP_SERVER_VARS['PHP_SELF'];
234 * This determines the location to forward to relative to your server.
235 * If this doesnt work correctly for you (although it should), you can
236 * remove all this code except the last two lines, and change the header()
237 * function to look something like this, customized to the location of
238 * SquirrelMail on your server:
240 * http://www.myhost.com/squirrelmail/src/login.php
242 function get_location () {
244 global $PHP_SELF, $SERVER_NAME, $HTTP_HOST, $SERVER_PORT,
247 /* Get the path, handle virtual directories */
248 $path = substr(php_self(), 0, strrpos(php_self(), '/'));
250 /* Check if this is a HTTPS or regular HTTP request. */
254 * If you have 'SSLOptions +StdEnvVars' in your apache config
255 * OR if you have HTTPS in your HTTP_SERVER_VARS
256 * OR if you are on port 443
258 $getEnvVar = getenv('HTTPS');
259 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
260 (isset($HTTP_SERVER_VARS['HTTPS'])) ||
261 (isset($HTTP_SERVER_VARS['SERVER_PORT']) &&
262 $HTTP_SERVER_VARS['SERVER_PORT'] == 443)) {
266 /* Get the hostname from the Host header or server config. */
268 if (isset($HTTP_HOST) && !empty($HTTP_HOST)) {
270 } else if (isset($SERVER_NAME) && !empty($SERVER_NAME)) {
271 $host = $SERVER_NAME;
272 } else if (isset($HTTP_SERVER_VARS['SERVER_NAME']) &&
273 !empty($HTTP_SERVER_VARS['SERVER_NAME'])) {
274 $host = $HTTP_SERVER_VARS['SERVER_NAME'];
279 if (! strstr($host, ':')) {
280 if (isset($SERVER_PORT)) {
281 if (($SERVER_PORT != 80 && $proto == 'http://')
282 ||
($SERVER_PORT != 443 && $proto == 'https://')) {
283 $port = sprintf(':%d', $SERVER_PORT);
288 /* Fallback is to omit the server name and use a relative */
289 /* URI, although this is not RFC 2616 compliant. */
290 return ($host ?
$proto . $host . $port . $path : $path);
295 * These functions are used to encrypt the passowrd before it is
296 * stored in a cookie.
298 function OneTimePadEncrypt ($string, $epad) {
299 $pad = base64_decode($epad);
301 for ($i = 0; $i < strlen ($string); $i++
) {
302 $encrypted .= chr (ord($string[$i]) ^
ord($pad[$i]));
305 return base64_encode($encrypted);
308 function OneTimePadDecrypt ($string, $epad) {
309 $pad = base64_decode($epad);
310 $encrypted = base64_decode ($string);
312 for ($i = 0; $i < strlen ($encrypted); $i++
) {
313 $decrypted .= chr (ord($encrypted[$i]) ^
ord($pad[$i]));
321 * Randomize the mt_rand() function. Toss this in strings or integers
322 * and it will seed the generator appropriately. With strings, it is
323 * better to get them long. Use md5() to lengthen smaller strings.
325 function sq_mt_seed($Val) {
326 /* if mt_getrandmax() does not return a 2^n - 1 number,
327 this might not work well. This uses $Max as a bitmask. */
328 $Max = mt_getrandmax();
330 if (! is_int($Val)) {
331 if (function_exists('crc32')) {
338 $HighBit = $Max ^
$Mask;
339 while ($Pos < strlen($Str)) {
340 if ($Val & $HighBit) {
341 $Val = (($Val & $Mask) << 1) +
1;
343 $Val = ($Val & $Mask) << 1;
359 mt_srand(($Val ^
mt_rand(0, $Max)) & $Max);
364 * This function initializes the random number generator fairly well.
365 * It also only initializes it once, so you don't accidentally get
366 * the same 'random' numbers twice in one session.
368 function sq_mt_randomize() {
369 global $REMOTE_PORT, $REMOTE_ADDR, $UNIQUE_ID;
377 sq_mt_seed((int)((double) microtime() * 1000000));
378 sq_mt_seed(md5($REMOTE_PORT . $REMOTE_ADDR . getmypid()));
381 if (function_exists('getrusage')) {
382 /* Avoid warnings with Win32 */
384 if (isset($dat) && is_array($dat)) {
386 foreach ($dat as $k => $v)
390 sq_mt_seed(md5($Str));
394 /* Apache-specific */
395 sq_mt_seed(md5($UNIQUE_ID));
400 function OneTimePadCreate ($length=100) {
404 for ($i = 0; $i < $length; $i++
) {
405 $pad .= chr(mt_rand(0,255));
408 return base64_encode($pad);
412 * Check if we have a required PHP-version. Return TRUE if we do,
413 * 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)
418 * Does not handle betas like 4.0.1b1 or development versions
420 function sqCheckPHPVersion($major, $minor, $release) {
423 eregi('^([0-9]+)\\.([0-9]+)(.*)', $ver, $regs);
425 /* Parse the version string. */
426 $vmajor = strval($regs[1]);
427 $vminor = strval($regs[2]);
429 if($vrel[0] == '.') {
430 $vrel = strval(substr($vrel, 1));
432 if($vrel[0] == 'b' ||
$vrel[0] == 'B') {
433 $vrel = - strval(substr($vrel, 1));
435 if($vrel[0] == 'r' ||
$vrel[0] == 'R') {
436 $vrel = - strval(substr($vrel, 2))/10;
439 /* Compare major version. */
440 if ($vmajor < $major) { return false; }
441 if ($vmajor > $major) { return true; }
443 /* Major is the same. Compare minor. */
444 if ($vminor < $minor) { return false; }
445 if ($vminor > $minor) { return true; }
447 /* Major and minor is the same as the required one. Compare release */
448 if ($vrel >= 0 && $release >= 0) { /* Neither are beta */
449 if($vrel < $release) return false;
450 } else if($vrel >= 0 && $release < 0) { /* This is not beta, required is beta */
452 } else if($vrel < 0 && $release >= 0){ /* This is beta, require not beta */
454 } else { /* Both are beta */
455 if($vrel > $release) return false;
462 * Returns a string showing the size of the message/attachment.
464 function show_readable_size($bytes) {
468 if ($bytes / 1024 > 1) {
475 settype($bytes, 'integer');
478 settype($bytes, 'integer');
481 return $bytes . '<small> ' . $type . '</small>';
485 * Generates a random string from the caracter set you pass in
488 * 1 = add lowercase a-z to $chars
489 * 2 = add uppercase A-Z to $chars
490 * 4 = add numbers 0-9 to $chars
493 function GenerateRandomString($size, $chars, $flags = 0) {
495 $chars .= 'abcdefghijklmnopqrstuvwxyz';
498 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
501 $chars .= '0123456789';
504 if (($size < 1) ||
(strlen($chars) < 1)) {
508 sq_mt_randomize(); /* Initialize the random number generator */
511 $j = strlen( $chars ) - 1;
512 while (strlen($String) < $size) {
513 $String .= $chars{mt_rand(0, $j)};
519 function quoteIMAP($str) {
520 return ereg_replace('(["\\])', '\\\\1', $str);
524 * Trims every element in the array
526 function TrimArray(&$array) {
527 foreach ($array as $k => $v) {
530 foreach ($
$k as $k2 => $v2) {
531 $
$k[$k2] = substr($v2, 1);
537 /* Re-assign back to array. */
543 * Removes slashes from every element in the array
545 function RemoveSlashes(&$array) {
546 foreach ($array as $k => $v) {
549 foreach ($
$k as $k2 => $v2) {
550 $newArray[stripslashes($k2)] = stripslashes($v2);
554 $
$k = stripslashes($v);
557 /* Re-assign back to the array. */
562 $PHP_SELF = php_self();