Subversion Repositories PEEPS

Rev

Rev 4 | Rev 6 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

#!/usr/bin/perl

# Redirect error messages to a log of my choosing. (it's annoying to filter for errors in the shared env)
#my $error_log_path = $ENV{SERVER_NAME} eq "volunteers.rollercon.com" ? "/home3/rollerco/logs/" : "/tmp/";
#close STDERR;
#open STDERR, '>>', $error_log_path.'vorc_error.log' or warn "Failed to open redirected logfile ($0): $!";
#warn "Redirecting errors to ${error_log_path}vorc_error.log";

use strict;
use PEEPS;
use tableViewer qw/inArray notInArray/;
use CGI qw/param cookie header start_html url url_param/;
use Email::Valid;
use WebDB;
use HTML::Tiny;
use Data::Dumper;
our $h = HTML::Tiny->new( mode => 'html' );
$ENV{HTTPS} = 'ON' if $ENV{SERVER_NAME} =~ /^peeps/;

my ($FORM, $cookie_string, $ERRMSG);
my @ERRORS;
my $dbh = getDBConnection ();
my @FIELDS = qw/ username derby_name derby_short_name email name_first name_middle name_last password active pronouns birthdate /;
my @PRIVFIELDS = qw/ email active /;


# The page's form might be submitted as a POST or a GET (or both?)
#  The initial _view_ likely comes as a GET request (making it easier to embed in an HREF as a URL)
#  Unpack any values sent in the GET and add them to the FORM hash
$FORM->{'SUB'} = WebDB::trim scalar param ('submit') // '';
$FORM->{'person_id'} = WebDB::trim scalar param ('person_id'); $FORM->{'person_id'} //= WebDB::trim scalar url_param ('person_id');
$FORM->{referer} = WebDB::trim scalar param ("referer") // "";
if ($FORM->{'SUB'} eq '') {
  if ($ENV{'REQUEST_URI'}) {
    my ($g, $keep) = split /\?/, $ENV{'REQUEST_URI'};
    if ($keep) {
      foreach (split /&/, $keep) {
        my ($k, $v) = split /=/;
        $k =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
        $v =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
        $k eq "submit" ? $FORM->{'SUB'} = $v : $FORM->{$k} = $v;
      }
    }
  }
}

# Keep track of the original referrer for the 'back' link/button
my $goback;
if ($FORM->{referer}) {
  $goback = $FORM->{referer};
} else {
  $goback = $ENV{HTTP_REFERER};
}

if ($FORM->{'SUB'} eq "Save") {
  process_form ($FORM);
} elsif ($FORM->{'SUB'} eq "New User") {
  display_form ("New", "New User"); # blank form
} elsif ($FORM->{'person_id'}) {
  display_form ($FORM->{'person_id'}, $FORM->{'SUB'});
} else {
  $cookie_string = authenticate (1);
  my ($EM, $PWD, $AL) = split /&/, $cookie_string;
  display_form (getUser ($EM)->{'person_id'}, "View");
}


sub process_form {
  my $F = shift // "";
  push @ERRORS, "Tried to save an empty form." and return unless $F;
  my $changed_username;

  $F->{username}       = WebDB::trim param ('username')   // '';
  $F->{email}       = lc WebDB::trim param ('email')   // '';
  $F->{password}    = WebDB::trim param ('password')   // '';
  $F->{derby_name}  = WebDB::trim param ('derby_name') // '';
  $F->{derby_short_name}  = WebDB::trim param ('derby_short_name') // '';
  $F->{name_first}   = WebDB::trim param ('name_first')  // '';
  $F->{name_middle}   = WebDB::trim param ('name_middle')  // '';
  $F->{name_last}   = WebDB::trim param ('name_last')  // '';
  $F->{pronouns}    = WebDB::trim param ('pronouns')   // '';
  $F->{birthdate}      = WebDB::trim param ('birthdate')     // '';
  $F->{person_id}        = param ('person_id')       // '';
  $F->{newaffiliation}   =  scalar param ('newaffiliation');
  $F->{deleteaffiliation}   = scalar param ('deleteaffiliation');
  
  if (defined $F->{newaffiliation}) { $F->{newaffiliation} = WebDB::trim $F->{newaffiliation}; } else { delete $F->{newaffiliation} };
  if (defined $F->{deleteaffiliation}) { $F->{deleteaffiliation} = WebDB::trim $F->{deleteaffiliation}; } else { delete $F->{deleteaffiliation} };
  
  if ($F->{person_id} eq "New") {
  # Saving a new User...
    # But first let's do some error checking...0
    my $warn_recovery = "Do you want to ".$h->a ({ href=>"recoverAccount"}, "Recover Your Account")." instead?";
    if (!$F->{username})  { push @ERRORS, "Blank Username!"; }
    if (checkDupes ('username', 'authentication', $F->{username})) { push @ERRORS, "Username already in use. ".$warn_recovery; $F->{username} = ""; }
    if (!$F->{password})   { push @ERRORS, "Blank Password!"; }
    if (!$F->{name_first})  { push @ERRORS, "Blank First Name!"; }
    if (!$F->{name_last})  { push @ERRORS, "Blank Last Name!"; }
#    if (!$F->{derby_name}) { $F->{derby_name} = $F->{real_name}; } # If they leave derby_name blank, use their real_name
#    if (checkDupes ('derby_name', $F->{derby_name})) { push @ERRORS, "Derby Name already in use. Pick a different one."; $F->{derby_name} = ""; }
    if (!$F->{email})      { push @ERRORS, "Blank Email!"; } else {
      $F->{email} =~ s/\s+//g; # make sure people aren't accidentally including spaces
      $F->{email} = lc $F->{email}; # sometimes people capitalize their email addresses and that's annoying...
      if (! Email::Valid->address (-address => $F->{email}, -mxcheck => 1, -tldcheck => 1)) { push @ERRORS, "Mal-formatted (or fake) Email Address!"; $F->{email} = ""; }
    }
    if (checkDupes ('email', 'person', $F->{email})) { push @ERRORS, "Email Address already in use. ".$warn_recovery; $F->{email} = ""; }
    
    if (scalar @ERRORS) {
      $ERRMSG = join $h->br, @ERRORS;
      display_form ("New", "New User", $ERRMSG, $F);
    } else {
      # We have a correctly formatted email address with a mail host record, go ahead and add the user
      
      $dbh->do ("insert into person (email, derby_name, derby_short_name, name_first, name_middle, name_last, pronouns, birthdate, created, updated)  values (?, password(?), ?, ?, ?, ?, ?, ?, ?, now(), now())", undef, 
                                  $F->{email}, $F->{derby_name}, $F->{derby_short_name}, $F->{name_first}, $F->{name_middle}, $F->{name_last}, $F->{pronouns}, $F->{birthdate})
        or display_form ("New", "New User", "ERROR: DB: ".$dbh->errstr, $F);

      ($F->{person_id}) = $dbh->selectrow_array ("select id from person where email = ?", undef, $F->{email});
      $dbh->do ("insert into authentication (person_id, username, password, activation) values (?, ?, password(?), md5(rand()))", undef, $F->{person_id}, $F->{username}, $F->{password});
      ($F->{activation}) = $dbh->selectrow_array ("select activation from authentication where person_id = ?", undef, $F->{person_id});
      
      $dbh->do ("replace into full_person select * from v_person where id = ?", undef, $F->{person_id});
    
      logit ($F->{person_id}, "New User Registration");
      sendNewUserEMail ("New User", $F);
      $cookie_string = authenticate (PEEPS::USER);
    }
  } else {
  # Save changes to an existing user.
    $cookie_string = authenticate (PEEPS::USER);
    my ($EM, $PWD, $AL) = split /&/, $cookie_string;
    
    my $OG = getUser ($F->{person_id});
    
#    if ($F->{derby_name} ne $OG->{derby_name} and checkDupes ('derby_name', $F->{derby_name})) { push @ERRORS, "Derby Name already in use. Pick a different one."; $F->{derby_name} = ""; }
#    if (!$F->{derby_name}) { push @ERRORS, "Blank Derby Name!"; }
    if (exists $F->{newaffiliation}) {
      push @ERRORS, "No League Selected." unless $F->{newaffiliation};
      push @ERRORS, "That's not a Member Org ID [$F->{newaffiliation}]!" if ($F->{newaffiliation} and $F->{newaffiliation} !~ /^\d+$/);
      push @ERRORS, "Already a member of ".getLeagueName ($F->{newaffiliation}) unless notInArray ($F->{newaffiliation}, [keys %{getLeagueAffiliation ($F->{person_id})}]);
    } elsif (exists $F->{deleteaffiliation}) {
      push @ERRORS, "No League Selected." unless $F->{deleteaffiliation};
      push @ERRORS, "That's not a Member Org ID [$F->{deleteaffiliation}]!" if ($F->{deleteaffiliation} and $F->{deleteaffiliation} !~ /^\d+$/);
      push @ERRORS, "Not a member of ".getLeagueName ($F->{deleteaffiliation}) if ($F->{deleteaffiliation} and notInArray ($F->{deleteaffiliation}, [keys %{getLeagueAffiliation ($F->{person_id})}]));
    } else {
      if ($F->{email} ne $OG->{email} and checkDupes ('email', 'person', $F->{email})) { push @ERRORS, "Email Address already in use. Pick a different one."; $F->{email} = ""; }
      if (!$F->{name_last})  { push @ERRORS, "Blank Last Name!"; }
      if (!$F->{name_first})  { push @ERRORS, "Blank First Name!"; }
    }
    
    if (scalar @ERRORS) {
      $ERRMSG = $h->br.join $h->br, @ERRORS;
      display_form ($F->{person_id}, (exists $F->{newaffiliation} or exists $F->{deleteaffiliation}) ? "View" : "Edit", $ERRMSG, $F);
    }
    
    
    if ($ORCUSER->{person_id} == $F->{person_id} or $AL >= PEEPS::SYSADMIN) {
    # They're editing their own record (or a sysadmin).
      
      if ($F->{newaffiliation}) {
    
        # warn "new league_id: ".$F->{newaffiliation};
        $dbh->do ("insert into role (member_org_id, person_id, role) values (?, ?, ?)", undef, $F->{newaffiliation}, $F->{person_id}, "Pending");
        
        if ($dbh->errstr) {
          my $dberr = $dbh->errstr;
          logit ($F->{person_id}, "DB ERROR ($dberr): Requesting league affiliation to ".getLeagueName ($F->{newaffiliation})." [$F->{newaffiliation}]");
          push @ERRORS, $dberr;
        } else {
          logit ($F->{person_id}, "Request to be added to ".getLeagueName ($F->{newaffiliation})." [$F->{newaffiliation}]");
          orglogit ($F->{person_id}, $F->{newaffiliation}, "Requested affiliation.");
        }
        
        $dbh->do ("replace into full_person select * from v_person where id = ? and league_id = ?", undef, $F->{person_id}, $F->{newaffiliation});
        
      } elsif ($F->{deleteaffiliation}) {
        # warn "delete league_id: ".$F->{deleteaffiliation};
        $dbh->do ("delete from role where member_org_id = ? and person_id = ?", undef, $F->{deleteaffiliation}, $F->{person_id});
        
        if ($dbh->errstr) {
          my $dberr = $dbh->errstr;
          logit ($F->{person_id}, "DB ERROR ($dberr): Deleting league affiliation from ".getLeagueName ($F->{deleteaffiliation})." [$F->{deleteaffiliation}]");
          push @ERRORS, $dberr;
        } else {
          logit ($F->{person_id}, "Deleted Affiliation with ".getLeagueName ($F->{deleteaffiliation})." [$F->{deleteaffiliation}]");
          orglogit ($F->{person_id}, $F->{deleteaffiliation}, "Removed affiliation.");
        }
        
        $dbh->do ("delete from full_person where id = ? and league_id = ?", undef, $F->{person_id}, $F->{deleteaffiliation});
        
        
      } else {
        foreach my $field (@FIELDS) {
          if ($F->{$field} eq $OG->{$field} or (($field eq "access" or $field eq "showme") and $F->{$field} == $OG->{$field}) or ($field eq "password" and !$F->{$field})) {
            # No changes to this field, move on...
            next;
          }
          
          if ($AL < PEEPS::SYSADMIN and inArray ($field, \@PRIVFIELDS)) {
            push @ERRORS, "ERROR: Only SysAdmins are allowed to change the $field field";
            logit ($F->{person_id}, "SECURITY: Only SysAdmins are allowed to change the $field field");
            next;
          }
          
          # warn "Changing $field: $F->{$field}";
          if (my $err = changeUser ($F->{person_id}, $field, $F->{$field})) {
            push @ERRORS, $err;
            logit ($F->{person_id}, "DB ERROR: Updating User Details: $err");
          }
        }
      }
    } else {
      push @ERRORS, "Attempting to update someone else's record, and you don't have permission to do that.";
      logit ($ORCUSER->{person_id}, "FAIL: You don't have access to update other people's user record");
    }
  }
  $F->{password} = "*******";
  $F->{buttons}   = $h->input ({ type=>"hidden", name=>"person_id", value=>$F->{person_id} }).$h->input ({ type=>"submit", name=>"submit", value=>"Edit" });

  if (scalar @ERRORS) {
    $ERRMSG = join ($h->br, @ERRORS);
  }
  
  display_form ($F->{person_id}, "View", $ERRMSG);
}

sub display_form {
  my $person_id = shift // "";
  my $view = shift; # // "New User";
  my $errors = shift // "";
  my $F = shift; # // "";
  
  if ($view eq 'Edit') {
    $cookie_string = authenticate (PEEPS::USER);
    my ($EM, $PWD, $AL) = split /&/, $cookie_string;
    $F = getUser ($person_id);
    
    if (canView ($ORCUSER, $F)) {
      # Editing your own record OR you're a lead/higher
      if (lc $EM eq lc $F->{email} or $ORCUSER->{access} < $F->{access}) {
        # If you're editing your own record, or someone who has higher access than you, make access level read-only
        #$F->{access}      = $h->input ({ type=>"hidden", name=>"access", value=>$F->{access} }).$AccessLevel->{$F->{access}};
      } else {
        #$F->{access}      = $h->select ({ name=>"access" }, [map { $F->{access} == $_ ? $h->option ({ value=>$_, selected=>[] }, $AccessLevel->{$_}) : $h->option ({ value=>$_ }, $AccessLevel->{$_}) } (-1..$ORCUSER->{access})]);
      }
      if ($AL == PEEPS::SYSADMIN) {
      # TBD:  allow users to change their email, but it'll re-initiate account activation...
        $F->{email}      = $h->input ({ type=>"text", name=>"email", value=>$F->{email} });
      } else {
        $F->{email}      = $F->{email}.$h->input ({ type=>"hidden", name=>"email", value=>$F->{email} });
      }
      if ($ORCUSER->{person_id} eq $F->{person_id} or $ORCUSER->{access} >= PEEPS::SYSADMIN) {
        $F->{username} = $h->input ({ type=>"text", name=>"username", value=>$F->{username} });
        $F->{password}   = $h->input ({ type=>"password", name=>"password" });
        $F->{derby_name} = $h->input ({ type=>"text", name=>"derby_name", value=>$F->{derby_name} });
        $F->{derby_short_name} = $h->input ({ type=>"text", name=>"derby_short_name", value=>$F->{derby_short_name} });
        $F->{name_first}  = $h->input ({ type=>"text", name=>"name_first", value=>$F->{name_first} });
        $F->{name_middle}  = $h->input ({ type=>"text", name=>"name_middle", value=>$F->{name_middle} });
        $F->{name_last}  = $h->input ({ type=>"text", name=>"name_last", value=>$F->{name_last} });
        $F->{pronouns}   = $h->input ({ type=>"text", name=>"pronouns", value=>$F->{pronouns} });
        $F->{birthdate}   = $h->input ({ type=>"date", name=>"birthdate", value=>$F->{birthdate} });
#        $F->{tshirt}     = $h->select ({ name=>"tshirt" }, [map { $F->{tshirt} eq $_ ? $h->option ({ selected=>[] }, $_) : $h->option ($_) } @tshirtOptions] );
        $F->{timeformat} = $h->select ({ name=>"timeformat" }, [map { $F->{timeformat} eq $_ ? $h->option ({ selected=>[] }, $_) : $h->option ($_) } qw(24hr ampm)] );
      } else {
        $F->{password}   = '*******';
      }
      $F->{person_id}       = $h->input ({ type=>"hidden", name=>"person_id", value=>$F->{person_id} })."$F->{person_id}&nbsp;";
      $F->{buttons}    = join " ", $h->input ({ type=>"submit", name=>"submit", value=>"Save" }), $h->input ({ type=>"reset", value=>"Reset" }), $h->input ({ type=>"submit", name=>"submit", value=>"Cancel" });
      
    } else {
      $ERRMSG = "Attempting to update someone else's record, and you don't have permission to do that.";
    }

  } elsif ($view eq 'New User') {
    $errors .= $h->br."NOTE: You will not be able to login until your account has been activated. Watch your email for further instructions.";
    # Skip authentication
    $F->{username}   = $h->input ({ type=>"text", name=>"username", value=>$F->{username} });
    $F->{email}      = $h->input ({ type=>"text", name=>"email", value=>$F->{email} });
    $F->{password}   = $h->input ({ type=>"password", name=>"password" });
    $F->{derby_name} = $h->input ({ type=>"text", name=>"derby_name", value=>$F->{derby_name} });
    $F->{derby_short_name} = $h->input ({ type=>"text", name=>"derby_short_name", value=>$F->{derby_short_name} });
    $F->{name_first}  = $h->input ({ type=>"text", name=>"name_first", value=>$F->{name_first} });
    $F->{name_middle}  = $h->input ({ type=>"text", name=>"name_middle", value=>$F->{name_middle} });
    $F->{name_last}  = $h->input ({ type=>"text", name=>"name_last", value=>$F->{name_last} });
    $F->{pronouns}   = $h->input ({ type=>"text", name=>"pronouns", value=>$F->{pronouns} });
    $F->{birthdate}   = $h->input ({ type=>"date", name=>"birthdate", value=>$F->{birthdate} });
#    $F->{timeformat} = $h->select ({ name=>"timeformat" }, [map { $F->{timeformat} eq $_ ? $h->option ({ selected=>[] }, $_) : $h->option ($_) } qw(24hr ampm)] );
    $F->{person_id}         = $h->input ({ type=>"hidden", name=>"person_id", value=>"New" })."TBD&nbsp;";
    
    $F->{buttons}   = $h->input ({ type=>"submit", name=>"submit", value=>"Save" })." ".$h->input ({ type=>"reset", value=>"Reset" })." ".$h->input ({ type=>"submit", name=>"submit", value=>"Cancel" });
    $cookie_string = '';
  } elsif ($view eq 'View' or $view eq 'Cancel' or $view =~ /Affiliation$/ or !$view) {
    $cookie_string = authenticate (1);
    my ($EM, $PWD, $AL) = split /&/, $cookie_string;
    
    if (!$view) {
      $F->{'person_id'} = getUser ($EM)->{'person_id'};
    }

    # Check to make sure they're only looking up their own ID unless they're a lead or higher
    my $targetuser = getUser ($person_id);
    
    if (!$targetuser) {
      $errors = "User [$person_id] not found.";
      $F->{person_id} = "&nbsp;";
    } elsif (canView ($ORCUSER, $targetuser)) {
      $F = $targetuser;
#      $F->{access} = $AccessLevel->{$F->{access}};
      $F->{'password'} = "*******";
      ($F->{username}, $F->{last_login}) = $dbh->selectrow_array ("select username, last_login from authentication where person_id = ?", undef, $F->{person_id});
      
      $F->{buttons}   = $h->input ({ type=>"hidden", name=>"person_id", value=>$F->{'person_id'} }).$h->input ({ type=>"submit", name=>"submit", value=>"Edit" });
      
    } else {
      logit ($ORCUSER->{person_id}, "SECURITY: $ORCUSER->{derby_name} attempted to view another user's ($person_id) info");
      $errors = "Unauthorized attempt to view another user.  This has been logged.";
      $person_id = "";
      $F->{email}       = "&nbsp;";
      $F->{password}    = "&nbsp;";
      $F->{derby_name}  = "&nbsp;";
      $F->{derby_short_name} = "&nbsp;";
      $F->{name_first}  = "&nbsp;";
      $F->{name_middle} = "&nbsp;";
      $F->{name_last}   = "&nbsp;";
      $F->{pronouns}    = "&nbsp;";
      $F->{birthdate}   = "&nbsp;";
      $F->{person_id}   = "&nbsp;";
      $F->{buttons}     = "&nbsp;";
    }

  }

  #---------------START THE HTML--------------------

  my $PEEPSAUTH_cookie = cookie (-name=>'PEEPSAUTH',-value=>"$cookie_string",-expires=>"+30m");

  print header (-cookie=>$PEEPSAUTH_cookie);

  #foreach (keys %ENV) {
  # warn "$_: $ENV{$_}\n<br>";
  #}

  if ($errors) {
    $errors = $h->div ({ class=>"error" }, $errors);
  } else {
    $errors = "";
  }
  
  printRCHeader ("User Manager");
  
  print $errors;
  print $h->open ("form", { action=>url, method=>'POST', name=>'UserForm', id=>'UserForm'  });
  print $h->input ({ type=>"hidden", name=>"referer", value=>$goback }),
    $h->div ({ class=>"index" }, [$h->p ({ class=>"heading" }, "User Details:"),
      $h->div ({ class=>"rTable", style=>"min-width: 0%;" },[
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Member ID: ",               $F->{person_id}) ]),
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Username: ",                $F->{username}) ]),
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Email: ",                   $F->{email}) ]),
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Password: ",                $F->{password}) ]),
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Derby Name: ",              $F->{derby_name}) ]),
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Derby Short Name: ",        $F->{derby_short_name}) ]),
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "First Name: ",              $F->{name_first}) ]),
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Middle Name: ",             $F->{name_middle}) ]),
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Last Name: ",               $F->{name_last}) ]),
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Pronouns: ",                $F->{pronouns}) ]),
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Birthdate: ",               $F->{birthdate}) ]),
#        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Time Format: ",       $F->{timeformat}) ]),
        $F->{person_id} =~ /^\d+$/ ? $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "User Added: ",              $F->{created}) ]) : "",
        $F->{person_id} =~ /^\d+$/ ? $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Last Login: ",              $F->{last_login}) ]) : "",
#        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "vORC Access Level: ",       $F->{access}) ]),
#        @printDepartments,
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCell" }, "&nbsp;") ]),
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr" }, $h->a ({ href=>$goback }, "[go back]"), $F->{buttons}) ])
      ])
    ]);
  my $YEAR = 1900 + (localtime)[5];
  
  my ($isAWFTDAAdmin)  = $dbh->selectrow_array ("select 1 from role where role = ? and member_org_id = ? and person_id = ?", undef, "System Admin", 4276, $ORCUSER->{person_id});
  
  # Display the list of roles per League Affiliation.  If the viewing user is a league (or wftda) admin, include a button to manage roles.
  my $leagues = getLeagueAffiliation($person_id);
  my @leagueroles;
  foreach (sort keys %{$leagues}) {
    my ($isALeagueAdmin) = inArray ($_, isLeagueAdmin ($ORCUSER->{person_id}));
    
    push @leagueroles, $h->div ({ class=>"rTableRow shaded", onClick=>"window.location.href='view_league?id=$_'" },[ 
                         $h->div ({ class=>"rTableCellr".($leagues->{$_}->[0] eq "Pending" ? " highlighted" : ""), style=>"font-size: smaller;".($leagues->{$_}->[0] eq "Pending" ? " font-style: italic;" : "") },
                           getLeagueName ($_),
                           join ($h->br, sort @{$leagues->{$_}}),
                           ($isALeagueAdmin or $isAWFTDAAdmin) ? $h->input ({type=>"button", onClick=>"event.stopPropagation(); window.location.href='manage_role?league_id=$_&person_id=$person_id'", value=>"Manage Role"}) : undef ) ]);
  }
  unshift (@leagueroles, $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableHead", style=>"font-size: smaller;" }, ($isAWFTDAAdmin or isLeagueAdmin ($ORCUSER->{person_id})) ? qw(League Role Admin) : qw(League Role) ) ]) );
  print $h->ul ([@leagueroles]);
  
  if ($FORM->{SUB} eq "Request League Affiliation") {
    print $h->ul ([
      $h->select ({ name => "newaffiliation" }, [$h->option (), map {$h->option ({value=>$_->[0]}, $_->[1])} @{ getLeagues ($person_id) } ] ),
      $h->input ( {type=>"submit", name=>"submit", value=>"Save" }).'&nbsp;'.$h->input ({ type=>"submit", name=>"submit", value=>"Cancel" })
    ]);
  } elsif ($F->{person_id} == $ORCUSER->{person_id}) {
    print $h->ul ($h->div ({ class=>"rTableRow" }, $h->input ({ type => "submit", name => "submit", value => "Request League Affiliation", onClick => "document.forms['UserForm'].requestSubmit();" })));
  }
  
  if ($FORM->{SUB} eq "Remove Affiliation") {
    print $h->ul ([
      $h->select ({ name => "deleteaffiliation", id=>'delaff' }, [$h->option (), map {$h->option ({value=>$_}, getLeagueName ($_))} sort keys %{$leagues} ] ),
      $h->input ( {type=>"submit", name=>"submit", value=>"Save", onClick=>"if (confirm('Are you sure you want to be removed from '+document.getElementById('delaff').options[document.getElementById('delaff').selectedIndex].text+'?')==true) {document.forms['UserForm'].requestSubmit();} else {return false;}" }).'&nbsp;'.$h->input ({ type=>"submit", name=>"submit", value=>"Cancel" })
    ]);
  } elsif ($F->{person_id} == $ORCUSER->{person_id}) {
    print $h->ul ($h->div ({ class=>"rTableRow" }, $h->input ({ type => "submit", name => "submit", value => "Remove Affiliation", onClick => "document.forms['UserForm'].requestSubmit();" })));
  }
  
  
  my @policyhistory = ($h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableHead", style=>"font-size: smaller;" }, qw(ID Policy Start End) ) ]));
  my @policy_columns = qw(id person_id member_org_id policy_name fee created start end terminated active);
  
  my @policies = @{ $dbh->selectall_arrayref ("select * from coverage where person_id = ? order by start desc, end", undef, $person_id) };
  my $active_policy = isPersonCovered ($person_id);
  foreach (@policies) {
    my %policy;
    @policy{@policy_columns} = @{$_};
    
    push @policyhistory, $h->div ({ class=>"rTableRow ".($policy{id} == $active_policy ? "highlighted" : "shaded"), onClick=>"window.location.href='view_policy?id=$policy{id}'" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: smaller;" }, $policy{id}, $policy{policy_name}, $policy{start}, $policy{end}) ]);
    
  #  push @classes, $h->div ({ class=>"rTableRow ".($classhash->{signedup} ? "highlighted" : "shaded"), onClick=>"window.location.href='view_class?id=$classid'" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: smaller;" }, @{$class}) ]);  
  }
  print $h->ul ([ @policyhistory ]) if (scalar @policies);
  
#  print $h->div ({ class=>"index" }, [
#                      $h->p ({ class=>"heading" }, "League Affiliation:"),
#                      $h->ul ({style=>"margin-right: 200px;"}, [
#                                map { $h->li ({class=>"shaded"},[
#                                                  $h->div ( {class=>"liLeft"}, getLeagueName ($_)),
#                                                  $h->div ( {class=>"liRight"}, join (", ", @{$leagues->{$_}}) )
#                                              ])
#                                    } sort keys %{$leagues}
#                              ]) 
#                ]) unless $person_id !~ /^\d+$/;
  
  
  print $h->div ({ class=>"index" }, [$h->p ({ class=>"heading" }, "Recent Activity:"), getLog ($person_id)]) unless $person_id !~ /^\d+$/;
  print $h->close ('form', 'body', 'html');
  exit;
}


sub checkDupes {
  my $field = shift;
  my $table = shift;
  my $nametocheck = shift;
  my $han = $dbh->prepare("select count(*) from $table where $field = ?");
  $han->execute($nametocheck);
  my ($person_id) = $han->fetchrow();
  return $person_id;
}

sub getLog {
  my $person_id = shift;
  
  my @activity_log;
  my $alog = $dbh->prepare("select timestamp, event from log where person_id = ? order by eventid desc limit 10");
  $alog->execute($person_id);
  while (my @logs = $alog->fetchrow_array) {
    push @activity_log, $h->li ({ class=>"shaded" }, join " ", @logs);
  }
  
  return $h->ul ([@activity_log]).$h->h5 ($h->a ({ href=>"log?filter-person_id=".$person_id }, "[Entire log history]"));
}

sub changeUser {
  my ($uid, $field, $newvalue) = @_;
  
  return "ERROR: Bad (or missing) person_id: [$uid]" unless $uid =~ /^\d+$/;
  return "ERROR: Bad (or missing) field name: [$field]" unless $field;
#  return "ERROR: Bad (or missing) new value: [$newvalue]" unless $newvalue;
  return "ERROR: Can't change someone's person_id" if $field eq "person_id";
  
  if ($field eq "password") {
    return unless $newvalue;
    $dbh->do ("update authentication set password = password(?) where person_id = ?", undef, $newvalue, $uid) or return "ERROR: ".$dbh->errstr;
  } else {
    my $table = ($field eq "username") ? "authentication" : "person";
    my $id    = ($field eq "username") ? "person_id" : "id";
    $dbh->do ("update $table set $field = ? where $id = ?", undef, $newvalue, $uid) or return "ERROR: ".$dbh->errstr;
    $dbh->do ("replace into full_person select * from v_person where id = ?", undef, $uid);
  }
  
  $newvalue = '********' if $field eq "password";
  if ($ORCUSER->{person_id} eq $uid) {
    logit ($uid, "Updated Profile: $field -> $newvalue");
  } else {
    logit ($ORCUSER->{person_id}, "Updated User [$uid]: $field -> $newvalue");
    logit ($uid, "$ORCUSER->{derby_name} updated your profile: $field -> $newvalue");
  }
  
  return;
}