#!/usr/bin/perl -w 


package esmith::FormMagick::Panel::groupmembers;

use strict;

use esmith::FormMagick;
use esmith::ConfigDB;
use esmith::AccountsDB;
use File::Basename;
use Exporter;
use Carp;

our @ISA = qw(esmith::FormMagick Exporter);

our @EXPORT = qw(

  show_initial
  genUsers
  modify_group
  get_accounts_prop
  get_description
  get_cgi_param
);

our $accounts = esmith::AccountsDB->open() || die "Couldn't open accounts";
our $db = esmith::ConfigDB->open || die "Couldn't open config db";

our $VERSION = sprintf '%d.%03d', q$Revision: 1.38 $ =~ /: (\d+).(\d+)/;



=pod 

=head1 NAME

esmith::FormMagick::Panels::groups - useful panel functions

=head1 SYNOPSIS

    use esmith::FormMagick::Panels::groups;

    my $panel = esmith::FormMagick::Panel::groups->new();
    $panel->display();

=head1 DESCRIPTION

=cut


=head2 new();

Exactly as for esmith::FormMagick

=begin testing

$ENV{ESMITH_ACCOUNT_DB} = "10e-smith-base/accounts.conf";
$ENV{ESMITH_CONFIG_DB} = "10e-smith-base/configuration.conf";

use_ok('esmith::FormMagick::Panel::groups');
use vars qw($panel);
ok($panel = esmith::FormMagick::Panel::groups->new(), "Create panel object");
isa_ok($panel, 'esmith::FormMagick::Panel::groups');

=end testing

=cut

sub new {
    shift;
    my $self = esmith::FormMagick->new();
    $self->{calling_package} = (caller)[0];
    bless $self;
    return $self;
}


=head1 ACCESSORS

=head2 get_cgi_param FM FIELD

Returns the named CGI parameter as a string

=cut

sub get_cgi_param {
    my $fm    = shift;
    my $param = shift;

    return ( $fm->{'cgi'}->param($param) );
}


=head2 get_accounts_prop ITEM PROP

A simple accessor for esmith::ConfigDB::Record::prop

=cut

sub get_accounts_prop {
    my $fm   = shift;
    my $item = shift;
    my $prop = shift;

    my $record = $accounts->get($item);

    if ($record) {
        return $record->prop($prop);
    }
    else {
        return '';
    }

}


=head2 get_description

Get the Description for the group named in the CGI argument "GroupName"

=cut

sub get_description {
    my $fm    = shift;
    my $group = $fm->{'cgi'}->param('groupName');
    return ( $fm->get_accounts_prop( $group, 'Description' ) );
}

=head1 ACTION


=head2 show_initial FM

Show the "start" page for this panel

=cut

sub show_initial () {
    my $fm = shift;
    my $q = $fm->{cgi};

	my $UserName = $ENV{'REMOTE_USER'} ||'';
	my $record = $accounts->get($UserName);
	my $dg=$record->prop('delegatedGroups')||'';
	$dg =~ s/ //g;
	my @g = split(/,/, $dg);
	my %delegatedGroups;
	foreach my $k (  @g )
		{
		$delegatedGroups{$k}=1;
		}
	
    $q->Delete('groupName');

    my $params = $fm->build_cgi_params();

    my $numGroups = $accounts->groups;

    if ( $numGroups == 0 ) {
        print $q->Tr($q->td(
	    '<p><b>' . $fm->localise("NO_GROUPS") . '</p></b>'));

    }
    else {
	print "<tr><th class=\"sme-border\">"
	    . $fm->localise("GROUP")
	    . "</th> <th class=\"sme-border\">"
	    . $fm->localise('DESCRIPTION')
	    . "</th><th class=\"sme-border\" colspan=\"2\">"
	    . $fm->localise('ACTION')
	    . "</th></tr>";
        foreach my $group ( $accounts->groups() ) {
			next if %delegatedGroups and not $delegatedGroups{$group->key};
            $params = $fm->build_cgi_params( $group->key );
            print "<tr>" . "<td class=\"sme-border\">"
              . $group->key . "</td>" . "<td class=\"sme-border\">"
              . $group->prop('Description') . "</td>"
              . "<td class=\"sme-border\"><a href=\"groupmembers?$params&wherenext=Modify\">"
              . $fm->localise("MODIFY") . "</a></td>"
              . "</tr>";

        }
        print $q->end_table,"\n";
    }
    return;
}


=head2 modify_group FM

Modify a group's description and membership roster

=cut

sub modify_group {

    my $fm = shift;
    my $q  = $fm->{'cgi'};

    my @members   = $q->param('groupMembers');
    my $groupName = $q->param('groupName');

    $accounts->get($groupName)->set_prop( 'Members', join ( ',', @members ) );

    # Untaint groupName before use in system()
    ($groupName) = ($groupName =~ /^([a-z][\-\_\.a-z0-9]*)$/);
    $fm->clear_params();
    return system("/sbin/e-smith/signal-event", "group-modify", "$groupName") ?
	$fm->error('MODIFY_ERROR') : $fm->success('MODIFIED_GROUP');
}


=head1  UTILITY FUNCTIONS

=head2 build_cgi_params()

Builds a CGI query string, using various sensible
defaults and esmith::FormMagick's props_to_query_string() method.

=cut

sub build_cgi_params {
    my ( $fm, $group ) = @_;

    my %props = (
        page       => 0,
        page_stack => "",
        ".id"      => $fm->{cgi}->param('.id') || "",
        groupName  => $group,
    );

    return $fm->props_to_query_string( \%props );
}

=head2 genUsers MEMBERS

Takes a comma delimited list of users and returns a string of 
html checkboxes for all system users with the members of the group
in $fm->{cgi}->parm('groupName')checked.

=cut

sub genUsers () {
    my $fm      = shift;
    my $members = "";
    my $group = $fm->{'cgi'}->param('groupName');

    if ($accounts->get($group)) {	
      $members = $accounts->get($group)->prop('Members');
    }	
    my %members;
    foreach my $member ( split ( /,/, $members ) ) {
        $members{$member} = 1;
    }
    my @users = sort { $a->key() cmp $b->key() } $accounts->users();

    # include Administrator at beginning of list

    my $out = "<tr>\n        <td class=\"sme-noborders-label\">"
      . $fm->localise('GROUP_MEMBERS')
      . "</td>\n        <td>\n"
      . "          <table border='0' cellspacing='0' cellpadding='0'>\n"
      . "            <tr>\n"
      . "              <td><input type=\"checkbox\" name=\"groupMembers\"";
    if ( $members{'admin'} ) {
        $out .= "checked";
    }
    $out .= " value=\"admin\"></td>\n              <td>Administrator (admin)</td>\n            </tr>\n";
    foreach my $user (@users) {
        my $checked = "";
        if ( $members{ $user->key() } ) {
            $checked = "checked";
        }
        my $name;
        if ( $user eq 'admin' ) { $name = 'Administrator'; }
        else {
            $name = $user->prop('FirstName') . " " . $user->prop('LastName');
        }

        $out .="            <tr>\n"
             . "              <td><input type=\"checkbox\" name=\"groupMembers\" $checked value=\""
          . $user->key
          . "\"></td>\n              <td>$name (".$user->key.")</td>\n            </tr>\n";

    }

    $out .= "          </table>\n        </td>\n    </tr>\n";
    return $out;
}

=head2 clear_params

This method clears-out the parameters used in form submission so that they are
not inadvertenly picked-up where they should not be.

=cut

sub clear_params
{
    my $self = shift;
    my $q = $self->{cgi};

    $q->delete('groupMembers');
    $q->delete('groupDesc');
    $q->delete('groupName');
}
