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.5 [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) {
29 $parts = explode($needle, $haystack);
30 $elem = array_pop($parts);
31 while ($elem == '' && count($parts)) {
32 $elem = array_pop($parts);
38 * If $haystack is a full mailbox name, and $needle is the mailbox
39 * separator character, returns the second last part of the full
40 * mailbox name (i.e. the mailbox's parent mailbox)
42 function readMailboxParent($haystack, $needle) {
43 if ($needle == '') return '';
44 $parts = explode($needle, $haystack);
45 $elem = array_pop($parts);
46 while ($elem == '' && count($parts)) {
47 $elem = array_pop($parts);
49 return join($needle, $parts);
53 * Returns the index of the first chunk of string $haystack that
54 * starts with non-white-space character, starting at position $pos.
55 * If there is no such chunk, returns -1.
57 function next_pos_minus_white ($haystack, $pos) {
58 $len = strlen($haystack);
60 /* Get the next character. */
61 $c = substr($haystack, $pos, 1);
63 /* Check the next character. */
64 if (($c != ' ') && ($c != "\t") && ($c != "\n") && ($c != "\r")) {
68 /* Increment position in string. */
75 * Wraps text at $wrap characters
77 * Has a problem with special HTML characters, so call this before
78 * you do character translation.
80 * Specifically, ' comes up as 5 characters instead of 1.
81 * This should not add newlines to the end of lines.
83 function sqWordWrap(&$line, $wrap) {
84 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
85 $beginning_spaces = $regs[1];
86 if (isset($regs[2])) {
87 $words = explode(' ', $regs[2]);
93 $line = $beginning_spaces;
95 while ($i < count($words)) {
96 /* Force one word to be on a line (minimum) */
98 $line_len = strlen($beginning_spaces) +
strlen($words[$i]) +
2;
99 if (isset($words[$i +
1]))
100 $line_len +
= strlen($words[$i +
1]);
103 /* Add more words (as long as they fit) */
104 while ($line_len < $wrap && $i < count($words)) {
105 $line .= ' ' . $words[$i];
107 if (isset($words[$i]))
108 $line_len +
= strlen($words[$i]) +
1;
113 /* Skip spaces if they are the first thing on a continued line */
114 while (!isset($words[$i]) && $i < count($words)) {
118 /* Go to the next line if we have more to process */
119 if ($i < count($words)) {
120 $line .= "\n" . $beginning_spaces;
127 * Does the opposite of sqWordWrap()
129 function sqUnWordWrap(&$body) {
130 $lines = explode("\n", $body);
132 $PreviousSpaces = '';
133 for ($i = 0; $i < count($lines); $i ++
) {
134 ereg("^([\t >]*)([^\t >].*)?$", $lines[$i], $regs);
135 $CurrentSpaces = $regs[1];
136 if (isset($regs[2])) {
137 $CurrentRest = $regs[2];
141 $PreviousSpaces = $CurrentSpaces;
143 } else if (($PreviousSpaces == $CurrentSpaces) /* Do the beginnings match */
144 && (strlen($lines[$i - 1]) > 65) /* Over 65 characters long */
145 && strlen($CurrentRest)) { /* and there's a line to continue with */
146 $body .= ' ' . $CurrentRest;
148 $body .= "\n" . $lines[$i];
149 $PreviousSpaces = $CurrentSpaces;
157 * Returns an array of email addresses.
158 * Be cautious of "user@host.com"
160 function parseAddrs($text) {
161 if (trim($text) == '')
163 $text = str_replace(' ', '', $text);
164 $text = ereg_replace('"[^"]*"', '', $text);
165 $text = ereg_replace('\\([^\\)]*\\)', '', $text);
166 $text = str_replace(',', ';', $text);
167 $array = explode(';', $text);
168 for ($i = 0; $i < count ($array); $i++
) {
169 $array[$i] = eregi_replace ('^.*[<]', '', $array[$i]);
170 $array[$i] = eregi_replace ('[>].*$', '', $array[$i]);
176 * Returns a line of comma separated email addresses from an array.
178 function getLineOfAddrs($array) {
179 if (is_array($array)) {
180 $to_line = implode(', ', $array);
181 $to_line = ereg_replace(', (, )+', ', ', $to_line);
182 $to_line = trim(ereg_replace('^, ', '', $to_line));
183 if( substr( $to_line, -1 ) == ',' )
184 $to_line = substr( $to_line, 0, -1 );
192 function translateText(&$body, $wrap_at, $charset) {
193 global $where, $what; /* from searching */
194 global $color; /* color theme */
196 require_once('../functions/url_parser.php');
198 $body_ary = explode("\n", $body);
200 for ($i=0; $i < count($body_ary); $i++
) {
201 $line = $body_ary[$i];
202 if (strlen($line) - 2 >= $wrap_at) {
203 sqWordWrap($line, $wrap_at);
205 $line = charset_decode($charset, $line);
206 $line = str_replace("\t", ' ', $line);
213 while ( $line <> '' ) {
214 if ($line[$pos] == ' ') {
216 } else if (strpos($line, '>', $pos) === $pos) {
225 if (! isset($color[14])) {
226 $color[14] = '#FF0000';
228 $line = '<FONT COLOR="' . $color[14] . '">' . $line . '</FONT>';
230 if (! isset($color[13])) {
231 $color[13] = '#800000';
233 $line = '<FONT COLOR="' . $color[13] . '">' . $line . '</FONT>';
236 $body_ary[$i] = $line;
238 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
241 function find_mailbox_name ($mailbox) {
242 if (ereg(" *\"([^\r\n\"]*)\"[ \r\n]*$", $mailbox, $regs))
244 ereg(" *([^ \r\n\"]*)[ \r\n]*$",$mailbox,$regs);
249 function php_self () {
250 global $PHP_SELF, $HTTP_SERVER_VARS;
252 if (isset($HTTP_SERVER_VARS['REQUEST_URI']) && !empty($HTTP_SERVER_VARS['REQUEST_URI']) ) {
253 return $HTTP_SERVER_VARS['REQUEST_URI'];
256 if (isset($PHP_SELF) && !empty($PHP_SELF)) {
258 } else if (isset($HTTP_SERVER_VARS['PHP_SELF']) &&
259 !empty($HTTP_SERVER_VARS['PHP_SELF'])) {
260 return $HTTP_SERVER_VARS['PHP_SELF'];
268 * This determines the location to forward to relative to your server.
269 * If this doesnt work correctly for you (although it should), you can
270 * remove all this code except the last two lines, and change the header()
271 * function to look something like this, customized to the location of
272 * SquirrelMail on your server:
274 * http://www.myhost.com/squirrelmail/src/login.php
276 function get_location () {
278 global $PHP_SELF, $SERVER_NAME, $HTTP_HOST, $SERVER_PORT,
281 /* Get the path, handle virtual directories */
282 $path = substr(php_self(), 0, strrpos(php_self(), '/'));
284 /* Check if this is a HTTPS or regular HTTP request. */
288 * If you have 'SSLOptions +StdEnvVars' in your apache config
289 * OR if you have HTTPS in your HTTP_SERVER_VARS
290 * OR if you are on port 443
292 $getEnvVar = getenv('HTTPS');
293 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
294 (isset($HTTP_SERVER_VARS['HTTPS'])) ||
295 (isset($HTTP_SERVER_VARS['SERVER_PORT']) &&
296 $HTTP_SERVER_VARS['SERVER_PORT'] == 443)) {
300 /* Get the hostname from the Host header or server config. */
302 if (isset($HTTP_HOST) && !empty($HTTP_HOST)) {
304 } else if (isset($SERVER_NAME) && !empty($SERVER_NAME)) {
305 $host = $SERVER_NAME;
306 } else if (isset($HTTP_SERVER_VARS['SERVER_NAME']) &&
307 !empty($HTTP_SERVER_VARS['SERVER_NAME'])) {
308 $host = $HTTP_SERVER_VARS['SERVER_NAME'];
313 if (! strstr($host, ':')) {
314 if (isset($SERVER_PORT)) {
315 if (($SERVER_PORT != 80 && $proto == 'http://')
316 ||
($SERVER_PORT != 443 && $proto == 'https://')) {
317 $port = sprintf(':%d', $SERVER_PORT);
322 /* Fallback is to omit the server name and use a relative */
323 /* URI, although this is not RFC 2616 compliant. */
324 return ($host ?
$proto . $host . $port . $path : $path);
329 * These functions are used to encrypt the passowrd before it is
330 * stored in a cookie.
332 function OneTimePadEncrypt ($string, $epad) {
333 $pad = base64_decode($epad);
335 for ($i = 0; $i < strlen ($string); $i++
) {
336 $encrypted .= chr (ord($string[$i]) ^
ord($pad[$i]));
339 return base64_encode($encrypted);
342 function OneTimePadDecrypt ($string, $epad) {
343 $pad = base64_decode($epad);
344 $encrypted = base64_decode ($string);
346 for ($i = 0; $i < strlen ($encrypted); $i++
) {
347 $decrypted .= chr (ord($encrypted[$i]) ^
ord($pad[$i]));
355 * Randomize the mt_rand() function. Toss this in strings or integers
356 * and it will seed the generator appropriately. With strings, it is
357 * better to get them long. Use md5() to lengthen smaller strings.
359 function sq_mt_seed($Val) {
360 /* if mt_getrandmax() does not return a 2^n - 1 number,
361 this might not work well. This uses $Max as a bitmask. */
362 $Max = mt_getrandmax();
364 if (! is_int($Val)) {
365 if (function_exists('crc32')) {
372 $HighBit = $Max ^
$Mask;
373 while ($Pos < strlen($Str)) {
374 if ($Val & $HighBit) {
375 $Val = (($Val & $Mask) << 1) +
1;
377 $Val = ($Val & $Mask) << 1;
393 mt_srand(($Val ^
mt_rand(0, $Max)) & $Max);
398 * This function initializes the random number generator fairly well.
399 * It also only initializes it once, so you don't accidentally get
400 * the same 'random' numbers twice in one session.
402 function sq_mt_randomize() {
403 global $REMOTE_PORT, $REMOTE_ADDR, $UNIQUE_ID;
411 sq_mt_seed((int)((double) microtime() * 1000000));
412 sq_mt_seed(md5($REMOTE_PORT . $REMOTE_ADDR . getmypid()));
415 if (function_exists('getrusage')) {
416 /* Avoid warnings with Win32 */
418 if (isset($dat) && is_array($dat)) {
420 foreach ($dat as $k => $v)
424 sq_mt_seed(md5($Str));
428 /* Apache-specific */
429 sq_mt_seed(md5($UNIQUE_ID));
434 function OneTimePadCreate ($length=100) {
438 for ($i = 0; $i < $length; $i++
) {
439 $pad .= chr(mt_rand(0,255));
442 return base64_encode($pad);
446 * Check if we have a required PHP-version. Return TRUE if we do,
447 * or FALSE if we don't.
449 * To check for 4.0.1, use sqCheckPHPVersion(4,0,1)
450 * To check for 4.0b3, use sqCheckPHPVersion(4,0,-3)
452 * Does not handle betas like 4.0.1b1 or development versions
454 function sqCheckPHPVersion($major, $minor, $release) {
457 eregi('^([0-9]+)\\.([0-9]+)(.*)', $ver, $regs);
459 /* Parse the version string. */
460 $vmajor = strval($regs[1]);
461 $vminor = strval($regs[2]);
463 if($vrel[0] == '.') {
464 $vrel = strval(substr($vrel, 1));
466 if($vrel[0] == 'b' ||
$vrel[0] == 'B') {
467 $vrel = - strval(substr($vrel, 1));
469 if($vrel[0] == 'r' ||
$vrel[0] == 'R') {
470 $vrel = - strval(substr($vrel, 2))/10;
473 /* Compare major version. */
474 if ($vmajor < $major) { return false; }
475 if ($vmajor > $major) { return true; }
477 /* Major is the same. Compare minor. */
478 if ($vminor < $minor) { return false; }
479 if ($vminor > $minor) { return true; }
481 /* Major and minor is the same as the required one. Compare release */
482 if ($vrel >= 0 && $release >= 0) { /* Neither are beta */
483 if($vrel < $release) return false;
484 } else if($vrel >= 0 && $release < 0) { /* This is not beta, required is beta */
486 } else if($vrel < 0 && $release >= 0){ /* This is beta, require not beta */
488 } else { /* Both are beta */
489 if($vrel > $release) return false;
496 * Returns a string showing the size of the message/attachment.
498 function show_readable_size($bytes) {
502 if ($bytes / 1024 > 1) {
509 settype($bytes, 'integer');
512 settype($bytes, 'integer');
515 return $bytes . '<small> ' . $type . '</small>';
519 * Generates a random string from the caracter set you pass in
522 * 1 = add lowercase a-z to $chars
523 * 2 = add uppercase A-Z to $chars
524 * 4 = add numbers 0-9 to $chars
527 function GenerateRandomString($size, $chars, $flags = 0) {
529 $chars .= 'abcdefghijklmnopqrstuvwxyz';
532 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
535 $chars .= '0123456789';
538 if (($size < 1) ||
(strlen($chars) < 1)) {
542 sq_mt_randomize(); /* Initialize the random number generator */
545 while (strlen($String) < $size) {
546 $String .= $chars[mt_rand(0, strlen($chars))];
552 function quoteIMAP($str) {
553 return ereg_replace('(["\\])', '\\\\1', $str);
557 * Trims every element in the array
559 function TrimArray(&$array) {
560 foreach ($array as $k => $v) {
563 foreach ($
$k as $k2 => $v2) {
564 $
$k[$k2] = substr($v2, 1);
570 /* Re-assign back to array. */
576 * Removes slashes from every element in the array
578 function RemoveSlashes(&$array) {
579 foreach ($array as $k => $v) {
582 foreach ($
$k as $k2 => $v2) {
583 $newArray[stripslashes($k2)] = stripslashes($v2);
587 $
$k = stripslashes($v);
590 /* Re-assign back to the array. */
595 $PHP_SELF = php_self();