75420fafeba908bcbc94f190e4d433cffbbe7d7f
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.3 [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);
76 /* Get the next character. */
77 $c = substr($haystack, $pos, 1);
79 /* Check the next character. */
80 if (($c != ' ') && ($c != "\t") && ($c != "\n") && ($c != "\r")) {
84 /* Increment position in string. */
91 * Wraps text at $wrap characters
93 * Has a problem with special HTML characters, so call this before
94 * you do character translation.
96 * Specifically, ' comes up as 5 characters instead of 1.
97 * This should not add newlines to the end of lines.
99 function sqWordWrap(&$line, $wrap) {
100 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
101 $beginning_spaces = $regs[1];
102 if (isset($regs[2])) {
103 $words = explode(' ', $regs[2]);
109 $line = $beginning_spaces;
111 while ($i < count($words)) {
112 // Force one word to be on a line (minimum)
114 $line_len = strlen($beginning_spaces) +
strlen($words[$i]) +
2;
115 if (isset($words[$i +
1]))
116 $line_len +
= strlen($words[$i +
1]);
119 // Add more words (as long as they fit)
120 while ($line_len < $wrap && $i < count($words)) {
121 $line .= ' ' . $words[$i];
123 if (isset($words[$i]))
124 $line_len +
= strlen($words[$i]) +
1;
129 // Skip spaces if they are the first thing on a continued line
130 while (!isset($words[$i]) && $i < count($words)) {
134 // Go to the next line if we have more to process
135 if ($i < count($words)) {
136 $line .= "\n" . $beginning_spaces;
143 * Does the opposite of sqWordWrap()
145 function sqUnWordWrap(&$body) {
146 $lines = explode("\n", $body);
148 $PreviousSpaces = "";
149 for ($i = 0; $i < count($lines); $i ++
) {
150 ereg("^([\t >]*)([^\t >].*)?$", $lines[$i], $regs);
151 $CurrentSpaces = $regs[1];
152 if (isset($regs[2])) {
153 $CurrentRest = $regs[2];
157 $PreviousSpaces = $CurrentSpaces;
159 } else if (($PreviousSpaces == $CurrentSpaces) // Do the beginnings match
160 && (strlen($lines[$i - 1]) > 65) // Over 65 characters long
161 && strlen($CurrentRest)) { // and there's a line to continue with
162 $body .= ' ' . $CurrentRest;
164 $body .= "\n" . $lines[$i];
165 $PreviousSpaces = $CurrentSpaces;
173 * Returns an array of email addresses.
174 * Be cautious of "user@host.com"
176 function parseAddrs($text) {
177 if (trim($text) == "")
179 $text = str_replace(' ', '', $text);
180 $text = ereg_replace('"[^"]*"', '', $text);
181 $text = ereg_replace('\\([^\\)]*\\)', '', $text);
182 $text = str_replace(',', ';', $text);
183 $array = explode(';', $text);
184 for ($i = 0; $i < count ($array); $i++
) {
185 $array[$i] = eregi_replace ("^.*[<]", '', $array[$i]);
186 $array[$i] = eregi_replace ("[>].*$", '', $array[$i]);
192 * Returns a line of comma separated email addresses from an array.
194 function getLineOfAddrs($array) {
195 if (is_array($array)) {
196 $to_line = implode(', ', $array);
197 $to_line = ereg_replace(', (, )+', ', ', $to_line);
198 $to_line = trim(ereg_replace('^, ', '', $to_line));
199 if( substr( $to_line, -1 ) == ',' )
200 $to_line = substr( $to_line, 0, -1 );
208 function translateText(&$body, $wrap_at, $charset) {
209 global $where, $what; // from searching
210 global $color; // color theme
212 require_once('../functions/url_parser.php');
214 $body_ary = explode("\n", $body);
216 for ($i=0; $i < count($body_ary); $i++
) {
217 $line = $body_ary[$i];
218 if (strlen($line) - 2 >= $wrap_at) {
219 sqWordWrap($line, $wrap_at);
221 $line = charset_decode($charset, $line);
222 $line = str_replace("\t", ' ', $line);
229 if ($line[$pos] == ' ') {
231 } else if (strpos($line, '>', $pos) === $pos) {
240 if (! isset($color[14])) {
241 $color[14] = '#FF0000';
243 $line = '<FONT COLOR="' . $color[14] . '">' . $line . '</FONT>';
245 if (! isset($color[13])) {
246 $color[13] = '#800000';
248 $line = '<FONT COLOR="' . $color[13] . '">' . $line . '</FONT>';
251 $body_ary[$i] = $line;
253 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
256 function find_mailbox_name ($mailbox) {
257 if (ereg(" *\"([^\r\n\"]*)\"[ \r\n]*$", $mailbox, $regs))
259 ereg(" *([^ \r\n\"]*)[ \r\n]*$",$mailbox,$regs);
265 * This determines the location to forward to relative to your server.
266 * If this doesnt work correctly for you (although it should), you can
267 * remove all this code except the last two lines, and change the header()
268 * function to look something like this, customized to the location of
269 * SquirrelMail on your server:
271 * http://www.myhost.com/squirrelmail/src/login.php
273 function get_location () {
275 global $PHP_SELF, $SERVER_NAME, $HTTP_HOST, $SERVER_PORT,
279 $path = substr($PHP_SELF, 0, strrpos($PHP_SELF, '/'));
281 /* Check if this is a HTTPS or regular HTTP request. */
285 * If you have 'SSLOptions +StdEnvVars' in your apache config
286 * OR if you have HTTPS in your HTTP_SERVER_VARS
287 * OR if you are on port 443
289 $getEnvVar = getenv('HTTPS');
290 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
291 (isset($HTTP_SERVER_VARS['HTTPS'])) ||
292 (isset($HTTP_SERVER_VARS['SERVER_PORT']) &&
293 $HTTP_SERVER_VARS['SERVER_PORT'] == 443)) {
297 // Get the hostname from the Host header or server config.
299 if (isset($HTTP_HOST) && !empty($HTTP_HOST)) {
301 } else if (isset($SERVER_NAME) && !empty($SERVER_NAME)) {
302 $host = $SERVER_NAME;
306 if (! strstr($host, ':')) {
307 if (isset($SERVER_PORT)) {
308 if (($SERVER_PORT != 80 && $proto == 'http://')
309 ||
($SERVER_PORT != 443 && $proto == 'https://')) {
310 $port = sprintf(':%d', $SERVER_PORT);
315 /* Fallback is to omit the server name and use a relative */
316 /* URI, although this is not RFC 2616 compliant. */
317 return ($host ?
$proto . $host . $port . $path : $path);
322 * These functions are used to encrypt the passowrd before it is
323 * stored in a cookie.
325 function OneTimePadEncrypt ($string, $epad) {
326 $pad = base64_decode($epad);
328 for ($i = 0; $i < strlen ($string); $i++
) {
329 $encrypted .= chr (ord($string[$i]) ^
ord($pad[$i]));
332 return base64_encode($encrypted);
335 function OneTimePadDecrypt ($string, $epad) {
336 $pad = base64_decode($epad);
337 $encrypted = base64_decode ($string);
339 for ($i = 0; $i < strlen ($encrypted); $i++
) {
340 $decrypted .= chr (ord($encrypted[$i]) ^
ord($pad[$i]));
348 * Randomize the mt_rand() function. Toss this in strings or integers
349 * and it will seed the generator appropriately. With strings, it is
350 * better to get them long. Use md5() to lengthen smaller strings.
352 function sq_mt_seed($Val) {
353 // if mt_getrandmax() does not return a 2^n - 1 number,
354 // this might not work well. This uses $Max as a bitmask.
355 $Max = mt_getrandmax();
357 if (! is_int($Val)) {
358 if (function_exists('crc32')) {
365 $HighBit = $Max ^
$Mask;
366 while ($Pos < strlen($Str)) {
367 if ($Val & $HighBit) {
368 $Val = (($Val & $Mask) << 1) +
1;
370 $Val = ($Val & $Mask) << 1;
386 mt_srand(($Val ^
mt_rand(0, $Max)) & $Max);
391 * This function initializes the random number generator fairly well.
392 * It also only initializes it once, so you don't accidentally get
393 * the same 'random' numbers twice in one session.
395 function sq_mt_randomize() {
396 global $REMOTE_PORT, $REMOTE_ADDR, $UNIQUE_ID;
404 sq_mt_seed((int)((double) microtime() * 1000000));
405 sq_mt_seed(md5($REMOTE_PORT . $REMOTE_ADDR . getmypid()));
408 if (function_exists('getrusage')) {
409 // Avoid warnings with Win32
411 if (isset($dat) && is_array($dat)) {
413 foreach ($dat as $k => $v)
417 sq_mt_seed(md5($Str));
422 sq_mt_seed(md5($UNIQUE_ID));
427 function OneTimePadCreate ($length=100) {
431 for ($i = 0; $i < $length; $i++
) {
432 $pad .= chr(mt_rand(0,255));
435 return base64_encode($pad);
439 * Check if we have a required PHP-version. Return TRUE if we do,
440 * or FALSE if we don't.
442 * To check for 4.0.1, use sqCheckPHPVersion(4,0,1)
443 * To check for 4.0b3, use sqCheckPHPVersion(4,0,-3)
445 * Does not handle betas like 4.0.1b1 or development versions
447 function sqCheckPHPVersion($major, $minor, $release) {
450 eregi('^([0-9]+)\\.([0-9]+)(.*)', $ver, $regs);
452 /* Parse the version string. */
453 $vmajor = strval($regs[1]);
454 $vminor = strval($regs[2]);
456 if($vrel[0] == ".") {
457 $vrel = strval(substr($vrel, 1));
459 if($vrel[0] == 'b' ||
$vrel[0] == 'B') {
460 $vrel = - strval(substr($vrel, 1));
462 if($vrel[0] == 'r' ||
$vrel[0] == 'R') {
463 $vrel = - strval(substr($vrel, 2))/10;
466 /* Compare major version. */
467 if ($vmajor < $major) { return false; }
468 if ($vmajor > $major) { return true; }
470 /* Major is the same. Compare minor. */
471 if ($vminor < $minor) { return false; }
472 if ($vminor > $minor) { return true; }
474 /* Major and minor is the same as the required one. Compare release */
475 if ($vrel >= 0 && $release >= 0) { // Neither are beta
476 if($vrel < $release) return false;
477 } else if($vrel >= 0 && $release < 0) { // This is not beta, required is beta
479 } else if($vrel < 0 && $release >= 0){ // This is beta, require not beta
481 } else { // Both are beta
482 if($vrel > $release) return false;
489 * Returns a string showing the size of the message/attachment.
491 function show_readable_size($bytes) {
495 if ($bytes / 1024 > 1) {
502 settype($bytes, 'integer');
505 settype($bytes, 'integer');
508 return $bytes . '<small> ' . $type . '</small>';
512 * Generates a random string from the caracter set you pass in
515 * 1 = add lowercase a-z to $chars
516 * 2 = add uppercase A-Z to $chars
517 * 4 = add numbers 0-9 to $chars
520 function GenerateRandomString($size, $chars, $flags = 0) {
522 $chars .= 'abcdefghijklmnopqrstuvwxyz';
525 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
528 $chars .= '0123456789';
531 if (($size < 1) ||
(strlen($chars) < 1)) {
535 sq_mt_randomize(); // Initialize the random number generator
538 while (strlen($String) < $size) {
539 $String .= $chars[mt_rand(0, strlen($chars))];
545 function quoteIMAP($str) {
546 return ereg_replace('(["\\])', '\\\\1', $str);
550 * Trims every element in the array
552 function TrimArray(&$array) {
553 foreach ($array as $k => $v) {
556 foreach ($
$k as $k2 => $v2) {
557 $
$k[$k2] = substr($v2, 1);
563 /* Re-assign back to array. */
569 * Removes slashes from every element in the array
571 function RemoveSlashes(&$array) {
572 foreach ($array as $k => $v) {
575 foreach ($
$k as $k2 => $v2) {
576 $newArray[stripslashes($k2)] = stripslashes($v2);
580 $
$k = stripslashes($v);
583 /* Re-assign back to the array. */