6 * Copyright (c) 1999-2001 The Squirrelmail Development 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.0 [cvs]';
38 * Count the number of occurances of $needle are in $haystack.
39 * $needle can be a character or string, and need not occur in $haystack
41 function countCharInString($haystack, $needle) {
42 if ($needle == '') return 0;
43 return count(explode($needle, $haystack));
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 readShortMailboxName($haystack, $needle) {
51 if ($needle == '') return $haystack;
52 $parts = explode($needle, $haystack);
53 $elem = array_pop($parts);
54 while ($elem == '' && count($parts))
56 $elem = array_pop($parts);
62 * Read from the back of $haystack until $needle is found, or the begining
63 * of the $haystack is reached. $needle is a single character
65 function readMailboxParent($haystack, $needle) {
66 if ($needle == '') return '';
67 $parts = explode($needle, $haystack);
68 $elem = array_pop($parts);
69 while ($elem == '' && count($parts))
71 $elem = array_pop($parts);
73 return join($needle, $parts);
77 * Searches for the next position in a string minus white space.
79 function next_pos_minus_white ($haystack, $pos) {
80 while (substr($haystack, $pos, 1) == ' ' ||
81 substr($haystack, $pos, 1) == "\t" ||
82 substr($haystack, $pos, 1) == "\n" ||
83 substr($haystack, $pos, 1) == "\r") {
84 if ($pos >= strlen($haystack))
92 * Wraps text at $wrap characters
94 * Has a problem with special HTML characters, so call this before
95 * you do character translation.
97 * Specifically, ' comes up as 5 characters instead of 1.
98 * This should not add newlines to the end of lines.
100 function sqWordWrap(&$line, $wrap) {
101 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
102 $beginning_spaces = $regs[1];
103 if (isset($regs[2])) {
104 $words = explode(' ', $regs[2]);
110 $line = $beginning_spaces;
112 while ($i < count($words)) {
113 // Force one word to be on a line (minimum)
115 $line_len = strlen($beginning_spaces) +
strlen($words[$i]) +
2;
116 if (isset($words[$i +
1]))
117 $line_len +
= strlen($words[$i +
1]);
120 // Add more words (as long as they fit)
121 while ($line_len < $wrap && $i < count($words)) {
122 $line .= ' ' . $words[$i];
124 if (isset($words[$i]))
125 $line_len +
= strlen($words[$i]) +
1;
130 // Skip spaces if they are the first thing on a continued line
131 while (!isset($words[$i]) && $i < count($words)) {
135 // Go to the next line if we have more to process
136 if ($i < count($words)) {
137 $line .= "\n" . $beginning_spaces;
144 * Does the opposite of sqWordWrap()
146 function sqUnWordWrap(&$body) {
147 $lines = explode("\n", $body);
149 $PreviousSpaces = "";
150 for ($i = 0; $i < count($lines); $i ++
) {
151 ereg("^([\t >]*)([^\t >].*)?$", $lines[$i], $regs);
152 $CurrentSpaces = $regs[1];
153 if (isset($regs[2])) {
154 $CurrentRest = $regs[2];
158 $PreviousSpaces = $CurrentSpaces;
160 } else if (($PreviousSpaces == $CurrentSpaces) // Do the beginnings match
161 && (strlen($lines[$i - 1]) > 65) // Over 65 characters long
162 && strlen($CurrentRest)) { // and there's a line to continue with
163 $body .= ' ' . $CurrentRest;
165 $body .= "\n" . $lines[$i];
166 $PreviousSpaces = $CurrentSpaces;
174 * Returns an array of email addresses.
175 * Be cautious of "user@host.com"
177 function parseAddrs($text) {
178 if (trim($text) == "")
180 $text = str_replace(' ', '', $text);
181 $text = ereg_replace('"[^"]*"', '', $text);
182 $text = ereg_replace('\\([^\\)]*\\)', '', $text);
183 $text = str_replace(',', ';', $text);
184 $array = explode(';', $text);
185 for ($i = 0; $i < count ($array); $i++
) {
186 $array[$i] = eregi_replace ("^.*[<]", '', $array[$i]);
187 $array[$i] = eregi_replace ("[>].*$", '', $array[$i]);
193 * Returns a line of comma separated email addresses from an array.
195 function getLineOfAddrs($array) {
196 if (is_array($array)) {
197 $to_line = implode(', ', $array);
198 $to_line = ereg_replace(', (, )+', ', ', $to_line);
199 $to_line = trim(ereg_replace('^, ', '', $to_line));
200 if( substr( $to_line, -1 ) == ',' )
201 $to_line = substr( $to_line, 0, -1 );
209 function translateText(&$body, $wrap_at, $charset) {
210 global $where, $what; // from searching
211 global $color; // color theme
213 require_once('../functions/url_parser.php');
215 $body_ary = explode("\n", $body);
217 for ($i=0; $i < count($body_ary); $i++
) {
218 $line = $body_ary[$i];
219 if (strlen($line) - 2 >= $wrap_at) {
220 sqWordWrap($line, $wrap_at);
222 $line = charset_decode($charset, $line);
223 $line = str_replace("\t", ' ', $line);
230 if ($line[$pos] == ' ') {
232 } else if (strpos($line, '>', $pos) === $pos) {
241 if (! isset($color[14])) {
242 $color[14] = '#FF0000';
244 $line = '<FONT COLOR="' . $color[14] . '">' . $line . '</FONT>';
246 if (! isset($color[13])) {
247 $color[13] = '#800000';
249 $line = '<FONT COLOR="' . $color[13] . '">' . $line . '</FONT>';
252 $body_ary[$i] = $line;
254 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
257 function find_mailbox_name ($mailbox) {
258 if (ereg(" *\"([^\r\n\"]*)\"[ \r\n]*$", $mailbox, $regs))
260 ereg(" *([^ \r\n\"]*)[ \r\n]*$",$mailbox,$regs);
266 * This determines the location to forward to relative to your server.
267 * If this doesnt work correctly for you (although it should), you can
268 * remove all this code except the last two lines, and change the header()
269 * function to look something like this, customized to the location of
270 * SquirrelMail on your server:
272 * http://www.myhost.com/squirrelmail/src/login.php
274 function get_location () {
276 global $PHP_SELF, $SERVER_NAME, $HTTP_HOST, $SERVER_PORT,
280 $path = substr($PHP_SELF, 0, strrpos($PHP_SELF, '/'));
282 /* Check if this is a HTTPS or regular HTTP request. */
286 * If you have 'SSLOptions +StdEnvVars' in your apache config
287 * OR if you have HTTPS in your HTTP_SERVER_VARS
288 * OR if you are on port 443
290 $getEnvVar = getenv('HTTPS');
291 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
292 (isset($HTTP_SERVER_VARS['HTTPS'])) ||
293 (isset($HTTP_SERVER_VARS['SERVER_PORT']) &&
294 $HTTP_SERVER_VARS['SERVER_PORT'] == 443)) {
298 // Get the hostname from the Host header or server config.
300 if (isset($HTTP_HOST) && !empty($HTTP_HOST)) {
302 } else if (isset($SERVER_NAME) && !empty($SERVER_NAME)) {
303 $host = $SERVER_NAME;
307 if (! strstr($host, ':')) {
308 if (isset($SERVER_PORT)) {
309 if (($SERVER_PORT != 80 && $proto == 'http://')
310 ||
($SERVER_PORT != 443 && $proto == 'https://')) {
311 $port = sprintf(':%d', $SERVER_PORT);
316 /* Fallback is to omit the server name and use a relative */
317 /* URI, although this is not RFC 2616 compliant. */
318 return ($host ?
$proto . $host . $port . $path : $path);
323 * These functions are used to encrypt the passowrd before it is
324 * stored in a cookie.
326 function OneTimePadEncrypt ($string, $epad) {
327 $pad = base64_decode($epad);
329 for ($i = 0; $i < strlen ($string); $i++
) {
330 $encrypted .= chr (ord($string[$i]) ^
ord($pad[$i]));
333 return base64_encode($encrypted);
336 function OneTimePadDecrypt ($string, $epad) {
337 $pad = base64_decode($epad);
338 $encrypted = base64_decode ($string);
340 for ($i = 0; $i < strlen ($encrypted); $i++
) {
341 $decrypted .= chr (ord($encrypted[$i]) ^
ord($pad[$i]));
349 * Randomize the mt_rand() function. Toss this in strings or integers
350 * and it will seed the generator appropriately. With strings, it is
351 * better to get them long. Use md5() to lengthen smaller strings.
353 function sq_mt_seed($Val) {
354 // if mt_getrandmax() does not return a 2^n - 1 number,
355 // this might not work well. This uses $Max as a bitmask.
356 $Max = mt_getrandmax();
358 if (! is_int($Val)) {
359 if (function_exists('crc32')) {
366 $HighBit = $Max ^
$Mask;
367 while ($Pos < strlen($Str)) {
368 if ($Val & $HighBit) {
369 $Val = (($Val & $Mask) << 1) +
1;
371 $Val = ($Val & $Mask) << 1;
387 mt_srand(($Val ^
mt_rand(0, $Max)) & $Max);
392 * This function initializes the random number generator fairly well.
393 * It also only initializes it once, so you don't accidentally get
394 * the same 'random' numbers twice in one session.
396 function sq_mt_randomize() {
397 global $REMOTE_PORT, $REMOTE_ADDR, $UNIQUE_ID;
405 sq_mt_seed((int)((double) microtime() * 1000000));
406 sq_mt_seed(md5($REMOTE_PORT . $REMOTE_ADDR . getmypid()));
409 if (function_exists('getrusage')) {
410 // Avoid warnings with Win32
412 if (isset($dat) && is_array($dat)) {
414 foreach ($dat as $k => $v)
418 sq_mt_seed(md5($Str));
423 sq_mt_seed(md5($UNIQUE_ID));
428 function OneTimePadCreate ($length=100) {
432 for ($i = 0; $i < $length; $i++
) {
433 $pad .= chr(mt_rand(0,255));
436 return base64_encode($pad);
440 * Check if we have a required PHP-version. Return TRUE if we do,
441 * or FALSE if we don't.
443 * To check for 4.0.1, use sqCheckPHPVersion(4,0,1)
444 * To check for 4.0b3, use sqCheckPHPVersion(4,0,-3)
446 * Does not handle betas like 4.0.1b1 or development versions
448 function sqCheckPHPVersion($major, $minor, $release) {
451 eregi('^([0-9]+)\\.([0-9]+)(.*)', $ver, $regs);
453 /* Parse the version string. */
454 $vmajor = strval($regs[1]);
455 $vminor = strval($regs[2]);
457 if($vrel[0] == ".") {
458 $vrel = strval(substr($vrel, 1));
460 if($vrel[0] == 'b' ||
$vrel[0] == 'B') {
461 $vrel = - strval(substr($vrel, 1));
463 if($vrel[0] == 'r' ||
$vrel[0] == 'R') {
464 $vrel = - strval(substr($vrel, 2))/10;
467 /* Compare major version. */
468 if ($vmajor < $major) { return false; }
469 if ($vmajor > $major) { return true; }
471 /* Major is the same. Compare minor. */
472 if ($vminor < $minor) { return false; }
473 if ($vminor > $minor) { return true; }
475 /* Major and minor is the same as the required one. Compare release */
476 if ($vrel >= 0 && $release >= 0) { // Neither are beta
477 if($vrel < $release) return false;
478 } else if($vrel >= 0 && $release < 0) { // This is not beta, required is beta
480 } else if($vrel < 0 && $release >= 0){ // This is beta, require not beta
482 } else { // Both are beta
483 if($vrel > $release) return false;
490 * Returns a string showing the size of the message/attachment.
492 function show_readable_size($bytes) {
496 if ($bytes / 1024 > 1) {
503 settype($bytes, 'integer');
506 settype($bytes, 'integer');
509 return $bytes . '<small> ' . $type . '</small>';
513 * Generates a random string from the caracter set you pass in
516 * 1 = add lowercase a-z to $chars
517 * 2 = add uppercase A-Z to $chars
518 * 4 = add numbers 0-9 to $chars
521 function GenerateRandomString($size, $chars, $flags = 0) {
523 $chars .= 'abcdefghijklmnopqrstuvwxyz';
526 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
529 $chars .= '0123456789';
532 if (($size < 1) ||
(strlen($chars) < 1)) {
536 sq_mt_randomize(); // Initialize the random number generator
539 while (strlen($String) < $size) {
540 $String .= $chars[mt_rand(0, strlen($chars))];
546 function quoteIMAP($str) {
547 return ereg_replace('(["\\])', '\\\\1', $str);
551 * Trims every element in the array
553 function TrimArray(&$array) {
554 foreach ($array as $k => $v) {
557 foreach ($
$k as $k2 => $v2) {
558 $
$k[$k2] = substr($v2, 1);
564 /* Re-assign back to array. */
570 * Removes slashes from every element in the array
572 function RemoveSlashes(&$array) {
573 foreach ($array as $k => $v) {
576 foreach ($
$k as $k2 => $v2) {
577 $newArray[stripslashes($k2)] = stripslashes($v2);
581 $
$k = stripslashes($v);
584 /* Re-assign back to the array. */