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);
42 * Returns the index of the first chunk of string $haystack that
43 * starts with non-white-space character, starting at position $pos.
44 * If there is no such chunk, returns -1.
46 function next_pos_minus_white ($haystack, $pos) {
47 $len = strlen($haystack);
49 /* Get the next character. */
50 $c = substr($haystack, $pos, 1);
52 /* Check the next character. */
53 if (($c != ' ') && ($c != "\t") && ($c != "\n") && ($c != "\r")) {
57 /* Increment position in string. */
64 * Wraps text at $wrap characters
66 * Has a problem with special HTML characters, so call this before
67 * you do character translation.
69 * Specifically, ' comes up as 5 characters instead of 1.
70 * This should not add newlines to the end of lines.
72 function sqWordWrap(&$line, $wrap) {
73 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
74 $beginning_spaces = $regs[1];
75 if (isset($regs[2])) {
76 $words = explode(' ', $regs[2]);
82 $line = $beginning_spaces;
84 while ($i < count($words)) {
85 /* Force one word to be on a line (minimum) */
87 $line_len = strlen($beginning_spaces) +
strlen($words[$i]) +
2;
88 if (isset($words[$i +
1]))
89 $line_len +
= strlen($words[$i +
1]);
92 /* Add more words (as long as they fit) */
93 while ($line_len < $wrap && $i < count($words)) {
94 $line .= ' ' . $words[$i];
96 if (isset($words[$i]))
97 $line_len +
= strlen($words[$i]) +
1;
102 /* Skip spaces if they are the first thing on a continued line */
103 while (!isset($words[$i]) && $i < count($words)) {
107 /* Go to the next line if we have more to process */
108 if ($i < count($words)) {
109 $line .= "\n" . $beginning_spaces;
116 * Does the opposite of sqWordWrap()
118 function sqUnWordWrap(&$body) {
119 $lines = explode("\n", $body);
121 $PreviousSpaces = '';
122 for ($i = 0; $i < count($lines); $i ++
) {
123 ereg("^([\t >]*)([^\t >].*)?$", $lines[$i], $regs);
124 $CurrentSpaces = $regs[1];
125 if (isset($regs[2])) {
126 $CurrentRest = $regs[2];
130 $PreviousSpaces = $CurrentSpaces;
132 } else if (($PreviousSpaces == $CurrentSpaces) /* Do the beginnings match */
133 && (strlen($lines[$i - 1]) > 65) /* Over 65 characters long */
134 && strlen($CurrentRest)) { /* and there's a line to continue with */
135 $body .= ' ' . $CurrentRest;
137 $body .= "\n" . $lines[$i];
138 $PreviousSpaces = $CurrentSpaces;
146 * Returns an array of email addresses.
147 * Be cautious of "user@host.com"
149 function parseAddrs($text) {
150 if (trim($text) == '')
152 $text = str_replace(' ', '', $text);
153 $text = ereg_replace('"[^"]*"', '', $text);
154 $text = ereg_replace('\\([^\\)]*\\)', '', $text);
155 $text = str_replace(',', ';', $text);
156 $array = explode(';', $text);
157 for ($i = 0; $i < count ($array); $i++
) {
158 $array[$i] = eregi_replace ('^.*[<]', '', $array[$i]);
159 $array[$i] = eregi_replace ('[>].*$', '', $array[$i]);
165 * Returns a line of comma separated email addresses from an array.
167 function getLineOfAddrs($array) {
168 if (is_array($array)) {
169 $to_line = implode(', ', $array);
170 $to_line = ereg_replace(', (, )+', ', ', $to_line);
171 $to_line = trim(ereg_replace('^, ', '', $to_line));
172 if( substr( $to_line, -1 ) == ',' )
173 $to_line = substr( $to_line, 0, -1 );
181 function translateText(&$body, $wrap_at, $charset) {
182 global $where, $what; /* from searching */
183 global $color; /* color theme */
185 require_once('../functions/url_parser.php');
187 $body_ary = explode("\n", $body);
189 for ($i=0; $i < count($body_ary); $i++
) {
190 $line = $body_ary[$i];
191 if (strlen($line) - 2 >= $wrap_at) {
192 sqWordWrap($line, $wrap_at);
194 $line = charset_decode($charset, $line);
195 $line = str_replace("\t", ' ', $line);
201 $j = strlen( $line );
203 while ( $pos < $j ) {
204 if ($line[$pos] == ' ') {
206 } else if (strpos($line, '>', $pos) === $pos) {
215 if (! isset($color[14])) {
216 $color[14] = '#FF0000';
218 $line = '<FONT COLOR="' . $color[14] . '">' . $line . '</FONT>';
220 if (! isset($color[13])) {
221 $color[13] = '#800000';
223 $line = '<FONT COLOR="' . $color[13] . '">' . $line . '</FONT>';
226 $body_ary[$i] = $line;
228 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
231 function find_mailbox_name ($mailbox) {
232 if (ereg(" *\"([^\r\n\"]*)\"[ \r\n]*$", $mailbox, $regs))
234 ereg(" *([^ \r\n\"]*)[ \r\n]*$",$mailbox,$regs);
239 function php_self () {
240 global $PHP_SELF, $HTTP_SERVER_VARS;
242 if (isset($HTTP_SERVER_VARS['REQUEST_URI']) && !empty($HTTP_SERVER_VARS['REQUEST_URI']) ) {
243 return $HTTP_SERVER_VARS['REQUEST_URI'];
246 if (isset($PHP_SELF) && !empty($PHP_SELF)) {
248 } else if (isset($HTTP_SERVER_VARS['PHP_SELF']) &&
249 !empty($HTTP_SERVER_VARS['PHP_SELF'])) {
250 return $HTTP_SERVER_VARS['PHP_SELF'];
258 * This determines the location to forward to relative to your server.
259 * If this doesnt work correctly for you (although it should), you can
260 * remove all this code except the last two lines, and change the header()
261 * function to look something like this, customized to the location of
262 * SquirrelMail on your server:
264 * http://www.myhost.com/squirrelmail/src/login.php
266 function get_location () {
268 global $PHP_SELF, $SERVER_NAME, $HTTP_HOST, $SERVER_PORT,
271 /* Get the path, handle virtual directories */
272 $path = substr(php_self(), 0, strrpos(php_self(), '/'));
274 /* Check if this is a HTTPS or regular HTTP request. */
278 * If you have 'SSLOptions +StdEnvVars' in your apache config
279 * OR if you have HTTPS in your HTTP_SERVER_VARS
280 * OR if you are on port 443
282 $getEnvVar = getenv('HTTPS');
283 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
284 (isset($HTTP_SERVER_VARS['HTTPS'])) ||
285 (isset($HTTP_SERVER_VARS['SERVER_PORT']) &&
286 $HTTP_SERVER_VARS['SERVER_PORT'] == 443)) {
290 /* Get the hostname from the Host header or server config. */
292 if (isset($HTTP_HOST) && !empty($HTTP_HOST)) {
294 } else if (isset($SERVER_NAME) && !empty($SERVER_NAME)) {
295 $host = $SERVER_NAME;
296 } else if (isset($HTTP_SERVER_VARS['SERVER_NAME']) &&
297 !empty($HTTP_SERVER_VARS['SERVER_NAME'])) {
298 $host = $HTTP_SERVER_VARS['SERVER_NAME'];
303 if (! strstr($host, ':')) {
304 if (isset($SERVER_PORT)) {
305 if (($SERVER_PORT != 80 && $proto == 'http://')
306 ||
($SERVER_PORT != 443 && $proto == 'https://')) {
307 $port = sprintf(':%d', $SERVER_PORT);
312 /* Fallback is to omit the server name and use a relative */
313 /* URI, although this is not RFC 2616 compliant. */
314 return ($host ?
$proto . $host . $port . $path : $path);
319 * These functions are used to encrypt the passowrd before it is
320 * stored in a cookie.
322 function OneTimePadEncrypt ($string, $epad) {
323 $pad = base64_decode($epad);
325 for ($i = 0; $i < strlen ($string); $i++
) {
326 $encrypted .= chr (ord($string[$i]) ^
ord($pad[$i]));
329 return base64_encode($encrypted);
332 function OneTimePadDecrypt ($string, $epad) {
333 $pad = base64_decode($epad);
334 $encrypted = base64_decode ($string);
336 for ($i = 0; $i < strlen ($encrypted); $i++
) {
337 $decrypted .= chr (ord($encrypted[$i]) ^
ord($pad[$i]));
345 * Randomize the mt_rand() function. Toss this in strings or integers
346 * and it will seed the generator appropriately. With strings, it is
347 * better to get them long. Use md5() to lengthen smaller strings.
349 function sq_mt_seed($Val) {
350 /* if mt_getrandmax() does not return a 2^n - 1 number,
351 this might not work well. This uses $Max as a bitmask. */
352 $Max = mt_getrandmax();
354 if (! is_int($Val)) {
355 if (function_exists('crc32')) {
362 $HighBit = $Max ^
$Mask;
363 while ($Pos < strlen($Str)) {
364 if ($Val & $HighBit) {
365 $Val = (($Val & $Mask) << 1) +
1;
367 $Val = ($Val & $Mask) << 1;
383 mt_srand(($Val ^
mt_rand(0, $Max)) & $Max);
388 * This function initializes the random number generator fairly well.
389 * It also only initializes it once, so you don't accidentally get
390 * the same 'random' numbers twice in one session.
392 function sq_mt_randomize() {
393 global $REMOTE_PORT, $REMOTE_ADDR, $UNIQUE_ID;
401 sq_mt_seed((int)((double) microtime() * 1000000));
402 sq_mt_seed(md5($REMOTE_PORT . $REMOTE_ADDR . getmypid()));
405 if (function_exists('getrusage')) {
406 /* Avoid warnings with Win32 */
408 if (isset($dat) && is_array($dat)) {
410 foreach ($dat as $k => $v)
414 sq_mt_seed(md5($Str));
418 /* Apache-specific */
419 sq_mt_seed(md5($UNIQUE_ID));
424 function OneTimePadCreate ($length=100) {
428 for ($i = 0; $i < $length; $i++
) {
429 $pad .= chr(mt_rand(0,255));
432 return base64_encode($pad);
436 * Check if we have a required PHP-version. Return TRUE if we do,
437 * or FALSE if we don't.
439 * To check for 4.0.1, use sqCheckPHPVersion(4,0,1)
440 * To check for 4.0b3, use sqCheckPHPVersion(4,0,-3)
442 * Does not handle betas like 4.0.1b1 or development versions
444 function sqCheckPHPVersion($major, $minor, $release) {
447 eregi('^([0-9]+)\\.([0-9]+)(.*)', $ver, $regs);
449 /* Parse the version string. */
450 $vmajor = strval($regs[1]);
451 $vminor = strval($regs[2]);
453 if($vrel[0] == '.') {
454 $vrel = strval(substr($vrel, 1));
456 if($vrel[0] == 'b' ||
$vrel[0] == 'B') {
457 $vrel = - strval(substr($vrel, 1));
459 if($vrel[0] == 'r' ||
$vrel[0] == 'R') {
460 $vrel = - strval(substr($vrel, 2))/10;
463 /* Compare major version. */
464 if ($vmajor < $major) { return false; }
465 if ($vmajor > $major) { return true; }
467 /* Major is the same. Compare minor. */
468 if ($vminor < $minor) { return false; }
469 if ($vminor > $minor) { return true; }
471 /* Major and minor is the same as the required one. Compare release */
472 if ($vrel >= 0 && $release >= 0) { /* Neither are beta */
473 if($vrel < $release) return false;
474 } else if($vrel >= 0 && $release < 0) { /* This is not beta, required is beta */
476 } else if($vrel < 0 && $release >= 0){ /* This is beta, require not beta */
478 } else { /* Both are beta */
479 if($vrel > $release) return false;
486 * Returns a string showing the size of the message/attachment.
488 function show_readable_size($bytes) {
492 if ($bytes / 1024 > 1) {
499 settype($bytes, 'integer');
502 settype($bytes, 'integer');
505 return $bytes . '<small> ' . $type . '</small>';
509 * Generates a random string from the caracter set you pass in
512 * 1 = add lowercase a-z to $chars
513 * 2 = add uppercase A-Z to $chars
514 * 4 = add numbers 0-9 to $chars
517 function GenerateRandomString($size, $chars, $flags = 0) {
519 $chars .= 'abcdefghijklmnopqrstuvwxyz';
522 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
525 $chars .= '0123456789';
528 if (($size < 1) ||
(strlen($chars) < 1)) {
532 sq_mt_randomize(); /* Initialize the random number generator */
535 $j = strlen( $chars ) - 1;
536 while (strlen($String) < $size) {
537 $String .= $chars{mt_rand(0, $j)};
543 function quoteIMAP($str) {
544 return ereg_replace('(["\\])', '\\\\1', $str);
548 * Trims every element in the array
550 function TrimArray(&$array) {
551 foreach ($array as $k => $v) {
554 foreach ($
$k as $k2 => $v2) {
555 $
$k[$k2] = substr($v2, 1);
561 /* Re-assign back to array. */
567 * Removes slashes from every element in the array
569 function RemoveSlashes(&$array) {
570 foreach ($array as $k => $v) {
573 foreach ($
$k as $k2 => $v2) {
574 $newArray[stripslashes($k2)] = stripslashes($v2);
578 $
$k = stripslashes($v);
581 /* Re-assign back to the array. */
586 $PHP_SELF = php_self();