# file-lib.pl
# Common functions for file manager CGIs

do '../web-lib.pl';
&init_config();
&switch_to_remote_user();
&create_user_config_dirs();

$real_home_dir = &resolve_links($remote_user_info[7]);

$icon_map = (	"c", 1,    "txt", 1,
		"pl", 1,   "cgi", 1,
		"html", 1, "htm", 1,
		"gif", 2,  "jpg", 2,
		"tar", 3
		);

$hide_dot_files = $userconfig{'hide_dot_files'};

# file_info_line(path)
# Returns a line of text containing encoded details of some file
sub file_info_line
{
local @st = $access{'follow'} ? stat($_[0]) : lstat($_[0]);
local $ext = $_[0] =~ /\S+\.([^\.\/]+)$/ ? $1 : undef;
local $user = getpwuid($st[4]); $user = $st[4] if (!$user);
local $group = getgrgid($st[5]); $group = $st[5] if (!$group);
local $rl = readlink($_[0]);
return sprintf ("%s\t%d\t%s\t%s\t%d\t%d\t%d\t%s",
		$_[0],
		(-l $_[0] && !$access{'follow'} ? 5 :
		 -d $_[0] ? 0 :
		 -b $_[0] ? 6 :
		 -c $_[0] ? 6 :
		 -p $_[0] ? 7 :
		 -S $_[0] ? 7 :
		 defined($icon_map{$ext}) ? $icon_map{$ext} : 4),
		$user, $group,
		$st[7], $st[2], $st[9], -l $_[0] && !$rl ? "???" : $rl);
}

# can_access(file)
sub can_access
{
return 1 if (!$config{'home_only'});
local @f = grep { $_ ne '' } split(/\//, $_[0]);
local $r;
DIR: foreach $r ($real_home_dir, split(/\s+/, $config{'root'})) {
	return 1 if ($r eq '/' || $_[0] eq '/' || $_[0] eq $r);
	local @a = grep { $_ ne '' } split(/\//, $r);
	local $i;
	for($i=0; $i<@a && $i<@f; $i++) {
		next DIR if ($a[$i] ne $f[$i]);
		}
	return 1;
	}
return 0;
}

# can_list(dir)
sub can_list
{
local @f = grep { $_ ne '' } split(/\//, $_[0]);
DIR: foreach $r ($real_home_dir, split(/\s+/, $config{'root'})) {
	return 1 if ($r eq '/' || $_[0] eq '/' || $_[0] eq $r);
	local @a = grep { $_ ne '' } split(/\//, $r);
	local $i;
	for($i=0; $i<@a && $i<@f; $i++) {
		next DIR if ($a[$i] ne $f[$i]);
		}
	return 1;
	}
return 0;
}

# accessible_subdir(dir)
# Returns the path to a dir under the given one that we can access
sub accessible_subdir
{
local ($r, @rv);
foreach $r ($real_home_dir, split(/\s+/, $config{'root'})) {
	if ($r =~ /^(\Q$_[0]\E\/[^\/]+)/) {
		push(@rv, $1);
		}
	}
return @rv;
}

# does nothing, because in usermin we have already always switched
sub switch_acl_uid
{
}

1;

