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.4 [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);
264 function php_self () {
265 global $PHP_SELF, $HTTP_SERVER_VARS;
267 if (isset($PHP_SELF) && !empty($PHP_SELF)) {
269 } else if (isset($HTTP_SERVER_VARS['PHP_SELF']) &&
270 !empty($HTTP_SERVER_VARS['PHP_SELF'])) {
271 return $HTTP_SERVER_VARS['PHP_SELF'];
279 * This determines the location to forward to relative to your server.
280 * If this doesnt work correctly for you (although it should), you can
281 * remove all this code except the last two lines, and change the header()
282 * function to look something like this, customized to the location of
283 * SquirrelMail on your server:
285 * http://www.myhost.com/squirrelmail/src/login.php
287 function get_location () {
289 global $PHP_SELF, $SERVER_NAME, $HTTP_HOST, $SERVER_PORT,
293 $path = substr($PHP_SELF, 0, strrpos($PHP_SELF, '/'));
295 /* Check if this is a HTTPS or regular HTTP request. */
299 * If you have 'SSLOptions +StdEnvVars' in your apache config
300 * OR if you have HTTPS in your HTTP_SERVER_VARS
301 * OR if you are on port 443
303 $getEnvVar = getenv('HTTPS');
304 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
305 (isset($HTTP_SERVER_VARS['HTTPS'])) ||
306 (isset($HTTP_SERVER_VARS['SERVER_PORT']) &&
307 $HTTP_SERVER_VARS['SERVER_PORT'] == 443)) {
311 // Get the hostname from the Host header or server config.
313 if (isset($HTTP_HOST) && !empty($HTTP_HOST)) {
315 } else if (isset($SERVER_NAME) && !empty($SERVER_NAME)) {
316 $host = $SERVER_NAME;
317 } else if (isset($HTTP_SERVER_VARS['SERVER_NAME']) &&
318 !empty($HTTP_SERVER_VARS['SERVER_NAME'])) {
319 $host = $HTTP_SERVER_VARS['SERVER_NAME'];
324 if (! strstr($host, ':')) {
325 if (isset($SERVER_PORT)) {
326 if (($SERVER_PORT != 80 && $proto == 'http://')
327 ||
($SERVER_PORT != 443 && $proto == 'https://')) {
328 $port = sprintf(':%d', $SERVER_PORT);
333 /* Fallback is to omit the server name and use a relative */
334 /* URI, although this is not RFC 2616 compliant. */
335 return ($host ?
$proto . $host . $port . $path : $path);
340 * These functions are used to encrypt the passowrd before it is
341 * stored in a cookie.
343 function OneTimePadEncrypt ($string, $epad) {
344 $pad = base64_decode($epad);
346 for ($i = 0; $i < strlen ($string); $i++
) {
347 $encrypted .= chr (ord($string[$i]) ^
ord($pad[$i]));
350 return base64_encode($encrypted);
353 function OneTimePadDecrypt ($string, $epad) {
354 $pad = base64_decode($epad);
355 $encrypted = base64_decode ($string);
357 for ($i = 0; $i < strlen ($encrypted); $i++
) {
358 $decrypted .= chr (ord($encrypted[$i]) ^
ord($pad[$i]));
366 * Randomize the mt_rand() function. Toss this in strings or integers
367 * and it will seed the generator appropriately. With strings, it is
368 * better to get them long. Use md5() to lengthen smaller strings.
370 function sq_mt_seed($Val) {
371 // if mt_getrandmax() does not return a 2^n - 1 number,
372 // this might not work well. This uses $Max as a bitmask.
373 $Max = mt_getrandmax();
375 if (! is_int($Val)) {
376 if (function_exists('crc32')) {
383 $HighBit = $Max ^
$Mask;
384 while ($Pos < strlen($Str)) {
385 if ($Val & $HighBit) {
386 $Val = (($Val & $Mask) << 1) +
1;
388 $Val = ($Val & $Mask) << 1;
404 mt_srand(($Val ^
mt_rand(0, $Max)) & $Max);
409 * This function initializes the random number generator fairly well.
410 * It also only initializes it once, so you don't accidentally get
411 * the same 'random' numbers twice in one session.
413 function sq_mt_randomize() {
414 global $REMOTE_PORT, $REMOTE_ADDR, $UNIQUE_ID;
422 sq_mt_seed((int)((double) microtime() * 1000000));
423 sq_mt_seed(md5($REMOTE_PORT . $REMOTE_ADDR . getmypid()));
426 if (function_exists('getrusage')) {
427 // Avoid warnings with Win32
429 if (isset($dat) && is_array($dat)) {
431 foreach ($dat as $k => $v)
435 sq_mt_seed(md5($Str));
440 sq_mt_seed(md5($UNIQUE_ID));
445 function OneTimePadCreate ($length=100) {
449 for ($i = 0; $i < $length; $i++
) {
450 $pad .= chr(mt_rand(0,255));
453 return base64_encode($pad);
457 * Check if we have a required PHP-version. Return TRUE if we do,
458 * or FALSE if we don't.
460 * To check for 4.0.1, use sqCheckPHPVersion(4,0,1)
461 * To check for 4.0b3, use sqCheckPHPVersion(4,0,-3)
463 * Does not handle betas like 4.0.1b1 or development versions
465 function sqCheckPHPVersion($major, $minor, $release) {
468 eregi('^([0-9]+)\\.([0-9]+)(.*)', $ver, $regs);
470 /* Parse the version string. */
471 $vmajor = strval($regs[1]);
472 $vminor = strval($regs[2]);
474 if($vrel[0] == ".") {
475 $vrel = strval(substr($vrel, 1));
477 if($vrel[0] == 'b' ||
$vrel[0] == 'B') {
478 $vrel = - strval(substr($vrel, 1));
480 if($vrel[0] == 'r' ||
$vrel[0] == 'R') {
481 $vrel = - strval(substr($vrel, 2))/10;
484 /* Compare major version. */
485 if ($vmajor < $major) { return false; }
486 if ($vmajor > $major) { return true; }
488 /* Major is the same. Compare minor. */
489 if ($vminor < $minor) { return false; }
490 if ($vminor > $minor) { return true; }
492 /* Major and minor is the same as the required one. Compare release */
493 if ($vrel >= 0 && $release >= 0) { // Neither are beta
494 if($vrel < $release) return false;
495 } else if($vrel >= 0 && $release < 0) { // This is not beta, required is beta
497 } else if($vrel < 0 && $release >= 0){ // This is beta, require not beta
499 } else { // Both are beta
500 if($vrel > $release) return false;
507 * Returns a string showing the size of the message/attachment.
509 function show_readable_size($bytes) {
513 if ($bytes / 1024 > 1) {
520 settype($bytes, 'integer');
523 settype($bytes, 'integer');
526 return $bytes . '<small> ' . $type . '</small>';
530 * Generates a random string from the caracter set you pass in
533 * 1 = add lowercase a-z to $chars
534 * 2 = add uppercase A-Z to $chars
535 * 4 = add numbers 0-9 to $chars
538 function GenerateRandomString($size, $chars, $flags = 0) {
540 $chars .= 'abcdefghijklmnopqrstuvwxyz';
543 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
546 $chars .= '0123456789';
549 if (($size < 1) ||
(strlen($chars) < 1)) {
553 sq_mt_randomize(); // Initialize the random number generator
556 while (strlen($String) < $size) {
557 $String .= $chars[mt_rand(0, strlen($chars))];
563 function quoteIMAP($str) {
564 return ereg_replace('(["\\])', '\\\\1', $str);
568 * Trims every element in the array
570 function TrimArray(&$array) {
571 foreach ($array as $k => $v) {
574 foreach ($
$k as $k2 => $v2) {
575 $
$k[$k2] = substr($v2, 1);
581 /* Re-assign back to array. */
587 * Removes slashes from every element in the array
589 function RemoveSlashes(&$array) {
590 foreach ($array as $k => $v) {
593 foreach ($
$k as $k2 => $v2) {
594 $newArray[stripslashes($k2)] = stripslashes($v2);
598 $
$k = stripslashes($v);
601 /* Re-assign back to the array. */
606 $PHP_SELF = php_self();