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.
15 /*****************************************************************/
16 /*** THIS FILE NEEDS TO HAVE ITS FORMATTING FIXED!!! ***/
17 /*** PLEASE DO SO AND REMOVE THIS COMMENT SECTION. ***/
18 /*** + Base level indent should begin at left margin, as ***/
19 /*** the comment and $version stuff below. ***/
20 /*** + All identation should consist of four space blocks ***/
21 /*** + Tab characters are evil. ***/
22 /*** + all comments should use "slash-star ... star-slash" ***/
23 /*** style -- no pound characters, no slash-slash style ***/
24 /*** + FLOW CONTROL STATEMENTS (if, while, etc) SHOULD ***/
25 /*** ALWAYS USE { AND } CHARACTERS!!! ***/
26 /*** + Please use ' instead of ", when possible. Note " ***/
27 /*** should always be used in _( ) function calls. ***/
28 /*** Thank you for your help making the SM code more readable. ***/
29 /*****************************************************************/
32 * SquirrelMail version number -- DO NOT CHANGE
35 $version = '1.2.2 [cvs]';
38 * If $haystack is a full mailbox name and $needle is the mailbox
39 * separator character, returns the last part of the mailbox name.
41 function readShortMailboxName($haystack, $needle) {
45 $parts = explode($needle, $haystack);
46 $elem = array_pop($parts);
47 while ($elem == '' && count($parts)) {
48 $elem = array_pop($parts);
54 * If $haystack is a full mailbox name, and $needle is the mailbox
55 * separator character, returns the second last part of the full
56 * mailbox name (i.e. the mailbox's parent mailbox)
58 function readMailboxParent($haystack, $needle) {
59 if ($needle == '') return '';
60 $parts = explode($needle, $haystack);
61 $elem = array_pop($parts);
62 while ($elem == '' && count($parts)) {
63 $elem = array_pop($parts);
65 return join($needle, $parts);
69 * Returns the index of the first chunk of string $haystack that
70 * starts with non-white-space character, starting at position $pos.
71 * If there is no such chunk, returns -1.
73 function next_pos_minus_white ($haystack, $pos) {
74 $len = strlen($haystack);
75 for ( ; $pos < $len; $pos++
) {
76 $char = substr($haystack, $pos, 1);
77 if ( $char != ' ' && $char != "\t" && $char != "\n" && $char != "\r" ) {
85 * Wraps text at $wrap characters
87 * Has a problem with special HTML characters, so call this before
88 * you do character translation.
90 * Specifically, ' comes up as 5 characters instead of 1.
91 * This should not add newlines to the end of lines.
93 function sqWordWrap(&$line, $wrap) {
94 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
95 $beginning_spaces = $regs[1];
96 if (isset($regs[2])) {
97 $words = explode(' ', $regs[2]);
103 $line = $beginning_spaces;
105 while ($i < count($words)) {
106 // Force one word to be on a line (minimum)
108 $line_len = strlen($beginning_spaces) +
strlen($words[$i]) +
2;
109 if (isset($words[$i +
1]))
110 $line_len +
= strlen($words[$i +
1]);
113 // Add more words (as long as they fit)
114 while ($line_len < $wrap && $i < count($words)) {
115 $line .= ' ' . $words[$i];
117 if (isset($words[$i]))
118 $line_len +
= strlen($words[$i]) +
1;
123 // Skip spaces if they are the first thing on a continued line
124 while (!isset($words[$i]) && $i < count($words)) {
128 // Go to the next line if we have more to process
129 if ($i < count($words)) {
130 $line .= "\n" . $beginning_spaces;
137 * Does the opposite of sqWordWrap()
139 function sqUnWordWrap(&$body) {
140 $lines = explode("\n", $body);
142 $PreviousSpaces = "";
143 for ($i = 0; $i < count($lines); $i ++
) {
144 ereg("^([\t >]*)([^\t >].*)?$", $lines[$i], $regs);
145 $CurrentSpaces = $regs[1];
146 if (isset($regs[2])) {
147 $CurrentRest = $regs[2];
151 $PreviousSpaces = $CurrentSpaces;
153 } else if (($PreviousSpaces == $CurrentSpaces) // Do the beginnings match
154 && (strlen($lines[$i - 1]) > 65) // Over 65 characters long
155 && strlen($CurrentRest)) { // and there's a line to continue with
156 $body .= ' ' . $CurrentRest;
158 $body .= "\n" . $lines[$i];
159 $PreviousSpaces = $CurrentSpaces;
167 * Returns an array of email addresses.
168 * Be cautious of "user@host.com"
170 function parseAddrs($text) {
171 if (trim($text) == "")
173 $text = str_replace(' ', '', $text);
174 $text = ereg_replace('"[^"]*"', '', $text);
175 $text = ereg_replace('\\([^\\)]*\\)', '', $text);
176 $text = str_replace(',', ';', $text);
177 $array = explode(';', $text);
178 for ($i = 0; $i < count ($array); $i++
) {
179 $array[$i] = eregi_replace ("^.*[<]", '', $array[$i]);
180 $array[$i] = eregi_replace ("[>].*$", '', $array[$i]);
186 * Returns a line of comma separated email addresses from an array.
188 function getLineOfAddrs($array) {
189 if (is_array($array)) {
190 $to_line = implode(', ', $array);
191 $to_line = ereg_replace(', (, )+', ', ', $to_line);
192 $to_line = trim(ereg_replace('^, ', '', $to_line));
193 if( substr( $to_line, -1 ) == ',' )
194 $to_line = substr( $to_line, 0, -1 );
202 function translateText(&$body, $wrap_at, $charset) {
203 global $where, $what; // from searching
204 global $color; // color theme
206 require_once('../functions/url_parser.php');
208 $body_ary = explode("\n", $body);
210 for ($i=0; $i < count($body_ary); $i++
) {
211 $line = $body_ary[$i];
212 if (strlen($line) - 2 >= $wrap_at) {
213 sqWordWrap($line, $wrap_at);
215 $line = charset_decode($charset, $line);
216 $line = str_replace("\t", ' ', $line);
223 if ($line[$pos] == ' ') {
225 } else if (strpos($line, '>', $pos) === $pos) {
234 if (! isset($color[14])) {
235 $color[14] = '#FF0000';
237 $line = '<FONT COLOR="' . $color[14] . '">' . $line . '</FONT>';
239 if (! isset($color[13])) {
240 $color[13] = '#800000';
242 $line = '<FONT COLOR="' . $color[13] . '">' . $line . '</FONT>';
245 $body_ary[$i] = $line;
247 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
250 function find_mailbox_name ($mailbox) {
251 if (ereg(" *\"([^\r\n\"]*)\"[ \r\n]*$", $mailbox, $regs))
253 ereg(" *([^ \r\n\"]*)[ \r\n]*$",$mailbox,$regs);
259 * This determines the location to forward to relative to your server.
260 * If this doesnt work correctly for you (although it should), you can
261 * remove all this code except the last two lines, and change the header()
262 * function to look something like this, customized to the location of
263 * SquirrelMail on your server:
265 * http://www.myhost.com/squirrelmail/src/login.php
267 function get_location () {
269 global $PHP_SELF, $SERVER_NAME, $HTTP_HOST, $SERVER_PORT,
273 $path = substr($PHP_SELF, 0, strrpos($PHP_SELF, '/'));
275 /* Check if this is a HTTPS or regular HTTP request. */
279 * If you have 'SSLOptions +StdEnvVars' in your apache config
280 * OR if you have HTTPS in your HTTP_SERVER_VARS
281 * OR if you are on port 443
283 $getEnvVar = getenv('HTTPS');
284 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
285 (isset($HTTP_SERVER_VARS['HTTPS'])) ||
286 (isset($HTTP_SERVER_VARS['SERVER_PORT']) &&
287 $HTTP_SERVER_VARS['SERVER_PORT'] == 443)) {
291 // Get the hostname from the Host header or server config.
293 if (isset($HTTP_HOST) && !empty($HTTP_HOST)) {
295 } else if (isset($SERVER_NAME) && !empty($SERVER_NAME)) {
296 $host = $SERVER_NAME;
300 if (! strstr($host, ':')) {
301 if (isset($SERVER_PORT)) {
302 if (($SERVER_PORT != 80 && $proto == 'http://')
303 ||
($SERVER_PORT != 443 && $proto == 'https://')) {
304 $port = sprintf(':%d', $SERVER_PORT);
309 /* Fallback is to omit the server name and use a relative */
310 /* URI, although this is not RFC 2616 compliant. */
311 return ($host ?
$proto . $host . $port . $path : $path);
316 * These functions are used to encrypt the passowrd before it is
317 * stored in a cookie.
319 function OneTimePadEncrypt ($string, $epad) {
320 $pad = base64_decode($epad);
322 for ($i = 0; $i < strlen ($string); $i++
) {
323 $encrypted .= chr (ord($string[$i]) ^
ord($pad[$i]));
326 return base64_encode($encrypted);
329 function OneTimePadDecrypt ($string, $epad) {
330 $pad = base64_decode($epad);
331 $encrypted = base64_decode ($string);
333 for ($i = 0; $i < strlen ($encrypted); $i++
) {
334 $decrypted .= chr (ord($encrypted[$i]) ^
ord($pad[$i]));
342 * Randomize the mt_rand() function. Toss this in strings or integers
343 * and it will seed the generator appropriately. With strings, it is
344 * better to get them long. Use md5() to lengthen smaller strings.
346 function sq_mt_seed($Val) {
347 // if mt_getrandmax() does not return a 2^n - 1 number,
348 // this might not work well. This uses $Max as a bitmask.
349 $Max = mt_getrandmax();
351 if (! is_int($Val)) {
352 if (function_exists('crc32')) {
359 $HighBit = $Max ^
$Mask;
360 while ($Pos < strlen($Str)) {
361 if ($Val & $HighBit) {
362 $Val = (($Val & $Mask) << 1) +
1;
364 $Val = ($Val & $Mask) << 1;
380 mt_srand(($Val ^
mt_rand(0, $Max)) & $Max);
385 * This function initializes the random number generator fairly well.
386 * It also only initializes it once, so you don't accidentally get
387 * the same 'random' numbers twice in one session.
389 function sq_mt_randomize() {
390 global $REMOTE_PORT, $REMOTE_ADDR, $UNIQUE_ID;
398 sq_mt_seed((int)((double) microtime() * 1000000));
399 sq_mt_seed(md5($REMOTE_PORT . $REMOTE_ADDR . getmypid()));
402 if (function_exists('getrusage')) {
403 // Avoid warnings with Win32
405 if (isset($dat) && is_array($dat)) {
407 foreach ($dat as $k => $v)
411 sq_mt_seed(md5($Str));
416 sq_mt_seed(md5($UNIQUE_ID));
421 function OneTimePadCreate ($length=100) {
425 for ($i = 0; $i < $length; $i++
) {
426 $pad .= chr(mt_rand(0,255));
429 return base64_encode($pad);
433 * Check if we have a required PHP-version. Return TRUE if we do,
434 * or FALSE if we don't.
436 * To check for 4.0.1, use sqCheckPHPVersion(4,0,1)
437 * To check for 4.0b3, use sqCheckPHPVersion(4,0,-3)
439 * Does not handle betas like 4.0.1b1 or development versions
441 function sqCheckPHPVersion($major, $minor, $release) {
444 eregi('^([0-9]+)\\.([0-9]+)(.*)', $ver, $regs);
446 /* Parse the version string. */
447 $vmajor = strval($regs[1]);
448 $vminor = strval($regs[2]);
450 if($vrel[0] == ".") {
451 $vrel = strval(substr($vrel, 1));
453 if($vrel[0] == 'b' ||
$vrel[0] == 'B') {
454 $vrel = - strval(substr($vrel, 1));
456 if($vrel[0] == 'r' ||
$vrel[0] == 'R') {
457 $vrel = - strval(substr($vrel, 2))/10;
460 /* Compare major version. */
461 if ($vmajor < $major) { return false; }
462 if ($vmajor > $major) { return true; }
464 /* Major is the same. Compare minor. */
465 if ($vminor < $minor) { return false; }
466 if ($vminor > $minor) { return true; }
468 /* Major and minor is the same as the required one. Compare release */
469 if ($vrel >= 0 && $release >= 0) { // Neither are beta
470 if($vrel < $release) return false;
471 } else if($vrel >= 0 && $release < 0) { // This is not beta, required is beta
473 } else if($vrel < 0 && $release >= 0){ // This is beta, require not beta
475 } else { // Both are beta
476 if($vrel > $release) return false;
483 * Returns a string showing the size of the message/attachment.
485 function show_readable_size($bytes) {
489 if ($bytes / 1024 > 1) {
496 settype($bytes, 'integer');
499 settype($bytes, 'integer');
502 return $bytes . '<small> ' . $type . '</small>';
506 * Generates a random string from the caracter set you pass in
509 * 1 = add lowercase a-z to $chars
510 * 2 = add uppercase A-Z to $chars
511 * 4 = add numbers 0-9 to $chars
514 function GenerateRandomString($size, $chars, $flags = 0) {
516 $chars .= 'abcdefghijklmnopqrstuvwxyz';
519 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
522 $chars .= '0123456789';
525 if (($size < 1) ||
(strlen($chars) < 1)) {
529 sq_mt_randomize(); // Initialize the random number generator
532 while (strlen($String) < $size) {
533 $String .= $chars[mt_rand(0, strlen($chars))];
539 function quoteIMAP($str) {
540 return ereg_replace('(["\\])', '\\\\1', $str);
544 * Trims every element in the array
546 function TrimArray(&$array) {
547 foreach ($array as $k => $v) {
550 foreach ($
$k as $k2 => $v2) {
551 $
$k[$k2] = substr($v2, 1);
557 /* Re-assign back to array. */
563 * Removes slashes from every element in the array
565 function RemoveSlashes(&$array) {
566 foreach ($array as $k => $v) {
569 foreach ($
$k as $k2 => $v2) {
570 $newArray[stripslashes($k2)] = stripslashes($v2);
574 $
$k = stripslashes($v);
577 /* Re-assign back to the array. */