#!/usr/local/bin/perl
# list_grants.cgi
# Display all granted privileges

require './postgresql-lib.pl';
$access{'users'} || &error($text{'grant_ecannot'});
&ui_print_header(undef, $text{'grant_title'}, "", "list_grants");

# Check for down databases
@str = &table_structure($config{'basedb'}, "pg_database");
foreach $f (@str) {
	$hasconn++ if ($f->{'field'} eq 'datallowconn');
	}
if ($hasconn) {
	$rv = &execute_sql($config{'basedb'}, "select datname,datallowconn from pg_database");
	foreach $r (@{$rv->{'data'}}) {
		$dbup{$r->[0]} = ($r->[1] =~ /^(t|1)/i);
		}
	}

@dblist = &list_databases();
foreach $d (@dblist) {
	next if (!$dbup{$d} && $hasconn);
	$t = &execute_sql($d, "select relname,reltype,relkind,relhasrules from pg_class");
	map { $type{$_->[0]} = $_->[2] eq 'r' && $_->[3] eq 't' ? 'v' : $_->[2] } @{$t->{'data'}};

	# Create table -> schema map
	# XXX
	foreach $tn (&list_tables($d)) {
		}

	$s = &execute_sql($d, 'select relname, relacl from pg_class where (relkind = \'r\' OR relkind = \'S\') and relname !~ \'^pg_\' order by relname');
	foreach $g (@{$s->{'data'}}) {
		$type = $type{$g->[0]};
		if (!$doneheader++) {
			print "<table border width=100%>\n";
			print "<tr $tb> <td><b>$text{'grant_tvi'}</b></td> ",
			      "<td><b>$text{'grant_type'}</b></td> ",
			      "<td><b>$text{'grant_db'}</b></td> ",
			      "<td><b>$text{'grant_users'}</b></td> </tr>\n";
			}
		print "<tr $cb>\n";
		print "<td><a href='edit_grant.cgi?db=$d&table=$g->[0]&",
		      "type=$type'>",&html_escape($g->[0]),"</a></td>\n";
		print "<td>",$text{"grant_$type"}."</td>\n";
		print "<td>",&html_escape($d),"</td>\n";
		print "<td>\n";
		$g->[1] =~ s/^\{//; $g->[1] =~ s/\}$//;
		@gr = grep { /=\S/ } map { /^"(.*)"$/ ? $1 : $_ } split(/,/, $g->[1]);
		foreach $gr (@gr) {
			print "&nbsp;|&nbsp;" if ($gr ne $gr[0]);
			if ($gr =~ /^=(\S+)/) {
				print $text{'grant_public'};
				}
			elsif ($gr =~ /^group\s+(\S+)=(\S+)/) {
				print &text('grant_group',
					"<tt>".&html_escape($1)."</tt>");
				}
			elsif ($gr =~ /^(\S+)=(\S+)$/) {
				print "<tt>".&html_escape($1)."</tt>";
				}
			}
		print "&nbsp;</td> </tr>\n";
		}
	}
if ($doneheader) {
	print "</table><p>\n";
	}
else {
	print "<b>$text{'grant_none'}</b><p>\n";
	}

&ui_print_footer("", $text{'index_return'});

