<?_code

 use strict;
 use vars qw(%FORM);

 my ($sth, $ret);
 my $mode = $FORM{'mode'};

 my $remote = LJ::get_remote();

 $mode ||= $FORM{'user'} ? "viewuser" : "intro";

 my $user = LJ::canonical_username($FORM{'user'});
 my $u;
 $u = LJ::load_user($user) if $user;
 
 if ($mode eq "intro")
 {
     $ret .= "<h1>capability class management</h1>\n";
     $ret .= "<form method='get'>";
     $ret .= "Modify capabilities for user: <input name='user' size='15'> <input type='submit' value=\"Load\">";
     $ret .= "</form>";

     return $ret;
 }

 if ($mode eq "save")
 {
     return "<b>Error:</b> requires post"
         unless (LJ::did_post());

     return"<b>Error:</b> You don't have access to change a user's capability class."
         unless (LJ::check_priv($remote, "admin", "*"));

     unless ($u) {
         $ret .= "Unknown user.\n";
         return $ret;
     }

     my @cap_add = ();
     my @cap_del = ();
     my $newcaps = $u->{caps};
     foreach my $n (sort { $a <=> $b } keys %LJ::CAP) {
         if ($FORM{"class_$n"}) {
             push @cap_add, $n;
             $newcaps |= (1 << $n);
         } else {
             push @cap_del, $n;
             $newcaps &= ~(1 << $n);
         }
     }

     # note which caps were changed and log $logmsg to statushistory
     my $add_txt = join(",", @cap_add);
     my $del_txt = join(",", @cap_del);
     LJ::statushistory_add($u->{'userid'}, $remote->{'userid'},
                           "capedit", "add: $add_txt, del: $del_txt\n");

     LJ::modify_caps($u, \@cap_add, \@cap_del)
         or return"<b>Error:</b> Unable to modify caps.";

     # $u->{caps} is now updated in memory for later in this request
     $u->{caps} = $newcaps;

     $ret .= "Saved.";
     $mode = "viewuser";
 }

 if ($mode eq "viewuser") 
 {
     $ret .= "<h1><a href='capedit.bml'>&lt;&lt;</a> edit user '$user'</h1>\n";

     unless ($u) {
         $ret .= "Unknown user.\n";
         return $ret;
     }

     $ret .= "<form method='post'>";
     $ret .= "<input type='hidden' name='mode' value='save'>\n";
     $ret .= "<input type='hidden' name='user' value='$user'>\n";
     foreach my $n (sort { $a <=> $b } keys %LJ::CAP)
     {
         my $on = ($u->{'caps'}+0) & (1 << $n);
         my $checked = $on ? " checked='1'" : "";
         $ret .= "<p><input type='checkbox' name='class_$n' value='1' id='class_$n' $checked> ";
         my $name = $LJ::CAP{$n}->{'_name'} || "Unnamed capability class \#$n";
         if ($on) { $ret .= "<b>"; }
         $ret .= "<label for='class_$n'>$name</label>";
         if ($on) { $ret .= "</b>"; }
     }
     
     $ret .= "<p><input type='submit' value='Save'>\n";
     $ret .= "</form>";

     return $ret;
 }

 return "Unknown mode.";

_code?><?_c <LJDEP>
lib: cgi-bin/ljlib.pl
form: htdocs/admin/capedit.bml
post: htdocs/admin/capedit.bml
</LJDEP _c?>
