# htpasswd-file-lib.pl
# Functions for reading and writing a .htpasswd format file
# XXX md5 and old password

if (!$module_name) {
	do '../web-lib.pl';
	&init_config();
	%access = &get_module_acl();
	}

# list_users([file])
# Returns an array of user names from the given file
sub list_users
{
local $file = $_[0] || $config{'file'};
if (!defined($list_authusers_cache{$file})) {
	$list_authusers_cache{$file} = [ ];
	local $_;
	local $lnum = 0;
	local $count = 0;
	open(HTPASSWD, $file);
	while(<HTPASSWD>) {
		if (/^(#?)\s*(\S+):(\S*)/) {
			push(@{$list_authusers_cache{$file}},
				  { 'user' => $2,
				    'pass' => $3,
				    'enabled' => !$1,
				    'file' => $file,
				    'line' => $lnum,
				    'index' => $count++ });
			}
		$lnum++;
		}
	close(HTPASSWD);
	}
return $list_authusers_cache{$file};
}

# modify_user(&user)
sub modify_user
{
local $lref = &read_file_lines($_[0]->{'file'});
$lref->[$_[0]->{'line'}] = ($_[0]->{'enabled'} ? "" : "#").
			   "$_[0]->{'user'}:$_[0]->{'pass'}";
&flush_file_lines();
}

# create_user(&user, [file])
sub create_user
{
$_[0]->{'file'} = $_[1] || $config{'file'};
local $lref = &read_file_lines($_[0]->{'file'});
$_[0]->{'line'} = @$lref;
push(@$lref, ($_[0]->{'enabled'} ? "" : "#").
	     "$_[0]->{'user'}:$_[0]->{'pass'}");
&flush_file_lines();
$_[0]->{'index'} = @{$list_authusers_cache{$_[0]->{'file'}}};
push(@{$list_authusers_cache{$_[0]->{'file'}}}, $_[0]);
}

# delete_user(&user)
sub delete_user
{
local $lref = &read_file_lines($_[0]->{'file'});
splice(@$lref, $_[0]->{'line'}, 1);
&flush_file_lines();
splice(@{$list_authusers_cache{$_[0]->{'file'}}}, $_[0]->{'index'}, 1);
map { $_->{'line'}-- if ($_->{'line'} > $_[0]->{'line'}) }
    @{$list_authusers_cache{$_[0]->{'file'}}};
}

# encrypt_password(string, [old], md5mode)
sub encrypt_password
{
&seed_random();
if ($_[2]) {
	&foreign_require("useradmin", "user-lib.pl");
	return &useradmin::encrypt_md5($_[0], $_[1]);
	}
else {
	local $salt = $_[1] || chr(int(rand(26))+65).chr(int(rand(26))+65);
	return crypt($_[0], $salt);
	}
}

1;

