Subversion Repositories VORC

Rev

Rev 122 | Rev 212 | 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 cPanelUserConfig;
use RollerCon;
use tableViewer qw/inArray/;
use CGI qw/param cookie header start_html url/;
use Email::Valid;
use WebDB;
use HTML::Tiny;
our $h = HTML::Tiny->new( mode => 'html' );

my ($FORM, $cookie_string, $ERRMSG);
my @ERRORS;
my $dbh = getRCDBH;
my $depts = getDepartments (); # HashRef of the department TLAs -> Display Names...
my $deptDesc = getDepartmentDescriptions ();
my $deptLink = getDepartmentLinks ();
my $AccessLevel = getAccessLevels;
my @tshirtOptions = ("", "MS", "MM", "ML", "MXL", "M2X", "M3X");
my @AUTODEPTS = map { $_->[0] } @{$dbh->selectall_arrayref ("select TLA from department where autoapprove = true")};
my @FIELDS = qw/ derby_name email real_name phone password access department tshirt pronouns timeformat showme /;
my @PRIVFIELDS = qw/ email access /;
$ORCUSER->{department} = ref $ORCUSER->{department} eq "HASH" ? $ORCUSER->{department} : convertDepartments($ORCUSER->{department});


# 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'} = param ('submit') // '';
$FORM->{'RCid'} = param ('RCid') // '';
$FORM->{referer} = 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->{'SUB'} eq "Make Current") {
  $dbh->do ("update official set last_login = now() where RCid = ?", undef, $FORM->{'RCid'}) unless $FORM->{'RCid'} !~ /^\d+$/;
  logit ($FORM->{'RCid'}, "An Admin updated last_login time to current.");
#  logit ($ORCUSER->{'RCid'}, "Updated user ($FORM->{'RCid'}) last_login time to current.");
  display_form ($FORM->{'RCid'}, "View");
} elsif ($FORM->{'SUB'} eq "Verify") {
  $cookie_string = authenticate (RollerCon::USER);
        validate_emt ($FORM->{RCid}, "add");
  display_form ($FORM->{'RCid'}, "View");
} elsif ($FORM->{'SUB'} eq "Remove") {
  $cookie_string = authenticate (RollerCon::USER);
        validate_emt ($FORM->{RCid}, "del");
  display_form ($FORM->{'RCid'}, "View");
} elsif ($FORM->{'RCid'}) {
  display_form ($FORM->{'RCid'}, $FORM->{'SUB'});
} else {
  $cookie_string = authenticate (1);
  my ($EM, $PWD, $AL) = split /&/, $cookie_string;
  display_form (getUser ($EM)->{'RCid'}, "View");
}


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

  $F->{email}       = lc WebDB::trim param ('email')   // '';
  $F->{password}    = WebDB::trim param ('password')   // '';
  $F->{derby_name}  = WebDB::trim param ('derby_name') // '';
  $F->{real_name}   = WebDB::trim param ('real_name')  // '';
  $F->{pronouns}    = WebDB::trim param ('pronouns')   // '';
  $F->{tshirt}      = WebDB::trim param ('tshirt')     // '';
  $F->{phone}       = WebDB::trim param ('phone')      // '';
  $F->{timeformat}  = WebDB::trim param ('timeformat') // '24hr';
  $F->{showme}      = WebDB::trim param ('showme') ? 1 : 0;
  $F->{EMTVerified} = WebDB::trim param ('EMTVerified') ? 1 : 0;
  $F->{RCid}        = param ('RCid')       // '';
  $F->{access}      = param ('access')     // 0;
  $F->{department}  = join ":", map { "$_-".param ("DEPT-".$_) } map { s/^DEPT-//; $_ } grep { param ($_) ne "" } grep { /^DEPT-/ } param ;
  
  if ($F->{RCid} eq "New") {
  # Saving a new User...
    # But first let's do some error checking...0
    if (!$F->{password})   { push @ERRORS, "Blank Password!"; }
    if (!$F->{real_name})  { push @ERRORS, "Blank Full 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 (User-ID)!"; } 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', $F->{email})) { push @ERRORS, "Email Address already in use. Pick a different one."; $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
      
      # Check to see if any of the departments they've requested are set to autoapprove.
      $F->{department} = convertDepartments $F->{department};
      map { $F->{department}->{$_} = inArray ($_, \@AUTODEPTS) } keys %{$F->{department}};
      $F->{department} = convertDepartments $F->{department};
      
      $dbh->do ("insert into official (email,  password,       derby_name,       real_name,       pronouns,       tshirt,       phone,       timeformat,       showme,       access, department, added, activation) values (?, password(?), ?, ?, ?, ?, ?, ?, ?, ?, ?, CONVERT_TZ(now(), 'America/Chicago', 'America/Los_Angeles'), md5(rand()))", undef, 
                                  $F->{email}, $F->{password}, $F->{derby_name}, $F->{real_name}, $F->{pronouns}, $F->{tshirt}, $F->{phone}, $F->{timeformat}, $F->{showme}, 0,      $F->{department})
        or display_form ("New", "New User", "ERROR: DB: ".$dbh->errstr, $F);

      ($F->{RCid}, $F->{activation}) = $dbh->selectrow_array ("select RCid, activation from official where email = ?", undef, $F->{email});
      
      $dbh->do ("replace into RCid_ticket_link select official.RCid, v_ticket.id, year(now()) from official join v_ticket on official.email = v_ticket.email and official.real_name = v_ticket.full_name where official.RCid = ?", undef, $F->{RCid});
      logit ($F->{RCid}, "New User Registration");
      sendNewUserEMail ("New User", $F);
      $cookie_string = authenticate (RollerCon::USER);
    }
  } else {
  # Save changes to an existing user.
    $cookie_string = authenticate (RollerCon::USER);
    my ($EM, $PWD, $AL) = split /&/, $cookie_string;
    
    my $OG = getUser ($F->{RCid});
    
    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 ($F->{email} ne $OG->{email} and checkDupes ('email', $F->{email})) { push @ERRORS, "Email Address already in use. Pick a different one."; $F->{email} = ""; }
    if (!$F->{real_name})  { push @ERRORS, "Blank Full Name!"; }
    
    if (scalar @ERRORS) {
      $ERRMSG = join $h->br, @ERRORS;
      display_form ($F->{RCid}, "Edit", $ERRMSG, $F);
    }
    
    
    if ($ORCUSER->{department}->{EMT} >= RollerCon::LEAD or $AL >= RollerCon::SYSADMIN) {
      # Check for changes to the emt_verified field...
      if ($F->{EMTVerified} != $OG->{emt_verified}) {
        warn "Updating emt_verified for $OG->{derby_name} - $F->{EMTVerified} vs $OG->{emt_verified}";
        validate_emt ($F->{RCid}, $F->{EMTVerified} ? "add" : "del");
      }
    }
    
    if ($ORCUSER->{RCid} == $F->{RCid} or $AL >= RollerCon::SYSADMIN) {
    # They're editing their own record (or a sysadmin).
      
      my $DBDepts = $OG->{department};
      if ($F->{department} ne $DBDepts and $AL < RollerCon::SYSADMIN) {
        # They're trying to change one of their own departments.
        my $FORMDepts = convertDepartments $F->{department};
        $DBDepts =   convertDepartments $DBDepts;
        # the only change to a dept should be a request to be added, some depts are auto-approved.
        map { $FORMDepts->{$_} = inArray ($_, \@AUTODEPTS) } keys %{$FORMDepts};
        # or they can retract their request
        map { do { delete $DBDepts->{$_} } if $DBDepts->{$_} == 0 and !defined $FORMDepts->{$_} } keys %{$DBDepts};
        # otherwise, keep the same depts as are in the DB (or have been auto-approved...)
        map { $FORMDepts->{$_} = max ($DBDepts->{$_}, $FORMDepts->{$_}) } keys %{$DBDepts};
        $F->{department} = convertDepartments $FORMDepts;
      }

      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 < RollerCon::SYSADMIN and inArray ($field, \@PRIVFIELDS)) {
          push @ERRORS, "ERROR: Only SysAdmins are allowed to change the $field field";
          logit ($F->{RCid}, "SECURITY: Only SysAdmins are allowed to change the $field field");
          next;
        }
        
        # warn "Changing $field: $F->{$field}";
        if (my $err = changeUser ($F->{RCid}, $field, $F->{$field})) {
          push @ERRORS, $err;
          logit ($F->{RCid}, "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->{RCid}, "FAIL: You don't have access to update other people's user record");
    }
  }
  $F->{password} = "*******";
  $F->{buttons}   = $h->input ({ type=>"hidden", name=>"RCid", value=>$F->{RCid} }).$h->input ({ type=>"submit", name=>"submit", value=>"Edit" });
  $F->{department} = convertDepartments ($F->{department});
  $dbh->do ("replace into RCid_ticket_link select official.RCid, v_ticket.id, year(now()) from official join v_ticket on official.email = v_ticket.email and official.real_name = v_ticket.full_name where official.RCid = ?", undef, $F->{RCid});

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

sub display_form {
  my $RCID = shift // "";
  my $view = shift; # // "New User";
  my $errors = shift // "";
  my $F = shift; # // "";
  
  if ($view eq 'Edit') {
    $cookie_string = authenticate (RollerCon::USER);
    my ($EM, $PWD, $AL) = split /&/, $cookie_string;
    $F = getUser ($RCID);
    
    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 ($ORCUSER->{access} >= RollerCon::MANAGER) {
        #this would be the place to test for other types of managers that can update the MVP Pass setting
        if ($F->{MVPid}) {
          $F->{MVPid} .= "->link to change...<-";
        }
      } else {
      }
      if ($AL == RollerCon::SYSADMIN) {
        $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->{RCid} eq $F->{RCid} or $ORCUSER->{access} >= RollerCon::SYSADMIN) {
        $F->{password}   = $h->input ({ type=>"password", name=>"password" });
        $F->{derby_name} = $h->input ({ type=>"text", name=>"derby_name", value=>$F->{derby_name} });
        $F->{real_name}  = $h->input ({ type=>"text", name=>"real_name", value=>$F->{real_name} });
        $F->{pronouns}   = $h->input ({ type=>"text", name=>"pronouns", value=>$F->{pronouns} });
        $F->{tshirt}     = $h->select ({ name=>"tshirt" }, [map { $F->{tshirt} eq $_ ? $h->option ({ selected=>[] }, $_) : $h->option ($_) } @tshirtOptions] );
        $F->{phone}      = $h->input ({ type=>"text", name=>"phone", value=>$F->{phone} });
        $F->{timeformat} = $h->select ({ name=>"timeformat" }, [map { $F->{timeformat} eq $_ ? $h->option ({ selected=>[] }, $_) : $h->option ($_) } qw(24hr ampm)] );
        if ($F->{showme}) {
          $F->{showme}   = $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>"showme", value=>1, checked=>[] }), $h->span ({ class=>"slider round" })]);          
        } else {
          $F->{showme}   = $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>"showme", value=>1 }), $h->span ({ class=>"slider round" })]);
        }
      } else {
        $F->{password}   = '*******';
      }
      $F->{RCid}       = $h->input ({ type=>"hidden", name=>"RCid", value=>$F->{RCid} })."$F->{RCid}&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" });
            
      $F->{department} = convertDepartments ($F->{department});
      if (exists $F->{department}->{EMT} and ($ORCUSER->{department}->{EMT} >= RollerCon::LEAD or $ORCUSER->{access} >= RollerCon::SYSADMIN)) {
        if ($F->{emt_verified}) {
          $F->{EMTVerified} = $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>"EMTVerified", value=>1, checked=>[] }), $h->span ({ class=>"slider round" })]);
        } else {
          $F->{EMTVerified} = $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>"EMTVerified", value=>1 }), $h->span ({ class=>"slider round" })]);
        }
      }
      
      foreach my $k (keys %{$depts}) {
        next if $k eq "CMP";
        if ($ORCUSER->{access} > 4) {
          # SysAdmin can change anyone's department level
          $F->{department}->{$k} = $h->select ({ name=>"DEPT-".$k }, [ $h->option ({ value=>"" }, ""), map { $_ eq $F->{department}->{$k} ? $h->option ({ value=>$_, selected=>[] }, $AccessLevel->{$_}) : $h->option ({ value=>$_ }, $AccessLevel->{$_}) } (0..4) ]);
        } elsif ($ORCUSER->{department}->{$k} > 1 and $ORCUSER->{department}->{$k} > $F->{department}->{$k}) {
          # Department Leads and above can change someone's level within the dept (up to their own level -1)
          $F->{department}->{$k} = $h->select ({ name=>"DEPT-".$k }, [ $h->option ({ value=>"" }, ""), map { $_ eq $F->{department}->{$k} ? $h->option ({ value=>$_, selected=>[] }, $AccessLevel->{$_}) : $h->option ({ value=>$_ }, $AccessLevel->{$_}) } (0..$ORCUSER->{department}->{$k}-1) ]);
        } else {
          # Or it's your own record, you can still submit a request to be added to the dept.
          if (!defined $F->{department}->{$k}) {
            $F->{department}->{$k} = $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>"DEPT-$k", value=>0 }), $h->span ({ class=>"slider round" })]) unless !inArray ($k, \@AUTODEPTS);
          } elsif ($F->{department}->{$k} == 0) {
            $F->{department}->{$k} = $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>"DEPT-$k", value=>0, checked=>[] }), $h->span ({ class=>"slider round" })]);
          }
        }
      }
    } 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->{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->{real_name}  = $h->input ({ type=>"text", name=>"real_name", value=>$F->{real_name} });
    $F->{pronouns}   = $h->input ({ type=>"text", name=>"pronouns", value=>$F->{pronouns} });
    $F->{tshirt}     = $h->select ({ name=>"tshirt" }, [map { $F->{tshirt} eq $_ ? $h->option ({ selected=>[] }, $_) : $h->option ($_) } @tshirtOptions] );
    $F->{phone}      = $h->input ({ type=>"text", name=>"phone", value=>$F->{phone} });
    $F->{timeformat} = $h->select ({ name=>"timeformat" }, [map { $F->{timeformat} eq $_ ? $h->option ({ selected=>[] }, $_) : $h->option ($_) } qw(24hr ampm)] );
    if ($F->{showme}) {
      $F->{showme}   = $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>"showme", value=>1, checked=>[] }), $h->span ({ class=>"slider round" })]);          
    } else {
      $F->{showme}   = $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>"showme", value=>1 }), $h->span ({ class=>"slider round" })]);
    }
    $F->{RCid}         = $h->input ({ type=>"hidden", name=>"RCid", value=>"New" })."TBD&nbsp;";
    $F->{access}      = $h->input ({ type=>"hidden", name=>"access", value=>0 })."0";
    
    $F->{department} = convertDepartments ($F->{department});
    foreach (sort keys %{$depts}) {
      next if $_ eq "CMP";
      next unless inArray($_, \@AUTODEPTS);
      if (defined param ("DEPT-$_")) {
        $F->{department}->{$_} = $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>"DEPT-$_", value=>0, checked=>[] }), $h->span ({ class=>"slider round" })]);
      } else {
        $F->{department}->{$_} = $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>"DEPT-$_", value=>0 }), $h->span ({ class=>"slider round" })]);
      }
    }
    $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) {
    $cookie_string = authenticate (1);
    my ($EM, $PWD, $AL) = split /&/, $cookie_string;

    if (!$view) {
      $F->{'RCid'} = getUser ($EM)->{'RCid'};
    }

    # Check to make sure they're only looking up their own ID unless they're a lead or higher
    my  $targetuser = getUser ($RCID);

    if (canView ($ORCUSER, $targetuser)) {
      $F = $targetuser;
      $F->{department} = convertDepartments ($F->{department});
      if (exists $F->{department}->{EMT}) {
        $F->{EMTVerified} = $F->{emt_verified} ? "True" : "False";
        if ($ORCUSER->{department}->{EMT} >= RollerCon::LEAD or $AL >= RollerCon::SYSADMIN) {
                                        if ($F->{emt_verified}) {
                                                $F->{EMTVerified} = "True"."&nbsp;&nbsp;".$h->input ({ type=>"submit", name=>"submit", value=>"Remove" });
                                        } else {
                                                $F->{EMTVerified} = "False"."&nbsp;&nbsp;".$h->input ({ type=>"submit", name=>"submit", value=>"Verify" });
                }
        }
      }
      $F->{access} = $AccessLevel->{$F->{access}};
      $F->{showme} = $F->{showme} ? "True" : "False";
      $F->{'password'} = "*******";
      $F->{buttons}   = $h->input ({ type=>"hidden", name=>"RCid", value=>$F->{'RCid'} }).$h->input ({ type=>"submit", name=>"submit", value=>"Edit" });
      
      if ($ORCUSER->{access} >= RollerCon::SYSADMIN or ($ORCUSER->{department} and $ORCUSER->{department}->{VCI} > 2)) {
        $F->{last_login} .= $h->input ({ type=>"submit", name=>"submit", value=>"Make Current" });
      }
      
      
      if ($ORCUSER->{access} > 2 or ($ORCUSER->{department} and $ORCUSER->{department}->{MVP} >= 2)) {
        if($F->{MVPid}) {
          $F->{MVPid} .= '&nbsp;&nbsp;' . $h->button ({ onClick=>"window.open('update_mvp_ticket.pl?change=Delete&RCid=$F->{RCid}&MVPid=$F->{MVPid}','Change MVP Ticket','resizable,height=260,width=370'); return false;" }, "Delete Match");          
        } else {
          $F->{MVPid} .= $h->button ({ onClick=>"window.open('update_mvp_ticket.pl?change=lookup&RCid=$F->{RCid}','Change MVP Ticket','resizable,height=260,width=370'); return false;" }, "Manual Match");
          my $possible_matches = $dbh->selectall_arrayref ("select id, full_name from v_ticket where isnull(RCid) = true and email = (select email from official where RCid = ?) union
            select id, full_name from v_ticket where isnull(RCid) = true and full_name = (select real_name from official where RCid = ?) union
            select id, full_name from v_ticket where isnull(RCid) = true and derby_name = (select derby_name from official where RCid = ?)", undef, $F->{RCid}, $F->{RCid}, $F->{RCid});
          
          foreach my $match (@$possible_matches) {
            my ($MVPid, $fullname) = @$match;
            
            $F->{MVPid} .= $h->div ({ class => "hint" }, ["Possible Match: @$match", '&nbsp;&nbsp;', $h->button ({ onClick=>"window.open('update_mvp_ticket.pl?change=add&RCid=$F->{RCid}&MVPid=$MVPid','Change MVP Ticket','resizable,height=260,width=370'); return false;" }, "Accept Match")]);
          }
        }
      }
    } else {
      logit ($ORCUSER->{RCid}, "SECURITY: $ORCUSER->{derby_name} attempted to view another user's ($RCID) info");
      $errors = "Unauthorized attempt to view another user.  This has been logged.";
      $RCID = "";
      $F->{email}      = "&nbsp;";
      $F->{password}   = "&nbsp;";
      $F->{derby_name} = "&nbsp;";
      $F->{real_name}  = "&nbsp;";
      $F->{pronouns}   = "&nbsp;";
      $F->{tshirt}     = "&nbsp;";
      $F->{phone}      = "&nbsp;";
      $F->{timeformat} = "&nbsp;";
      $F->{showme}     = "&nbsp;";
      $F->{RCid}       = "&nbsp;";
      $F->{access}     = "&nbsp;";
      $F->{MVPid}      = "&nbsp;";
      $F->{buttons}    = "&nbsp;";
    }

  }

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

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

  print header (-cookie=>$RCAUTH_cookie);

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

  if ($errors) {
    $errors = $h->div ({ class=>"error" }, $errors);
  } else {
    $errors = "";
  }
  
   my @printDepartments = ( $h->div ({ class=>"index", style=>"display: unset;" }, $h->p ({ class=>"heading" }, "Volunteer Department Access:")) );
  push @printDepartments, $h->div ({ class=>"rTableRowSpan" },[ $h->div ({ style=>"rTableCellr" }, $h->div ({ class=>"hint" }, "Here is where you're signed up to volunteer at RollerCon:")) ]);
  foreach (sort grep { !/^PER$/ } keys %{$F->{department}}) {
    push @printDepartments, $h->div ({ class=>"rTableRow" }, [
      $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, 
        [ $h->span ({ class=>"tooltip-wrap" }, [$h->img ({src=>"/images/qm.png", width=>"18", height=>"18"}), $h->div ({ class=>"tooltip-content" }, $h->div ({class=>"bold"}, $depts->{$_}).$deptDesc->{$_} . (exists $deptLink->{$_} ? $h->a ({ href=>$deptLink->{$_}, target=>"_new"}, " [More Info]") : "") )]), $depts->{$_}.":" ],
        $F->{department}->{$_} =~ /^\d$/ ? $AccessLevel->{$F->{department}->{$_}} : $F->{department}->{$_}),
    ]);
  }

  printRCHeader ("User Manager");
  
  print $errors;
  print $h->form ({ action=>url, method=>'POST', name=>'Req' },[
    $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;" }, "User-ID / Email Address: ", $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;" }, "Full Name: ",               $F->{real_name}) ]),
        $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;" }, "TShirt Size: ",             $F->{tshirt}) ]),
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Phone: ",                   $F->{phone}) ]),
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Time Format: ",       $F->{timeformat}) ]),
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Share My Shifts: ",         $F->{showme}) ]),
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Database ID: ",             $F->{RCid}) ]),
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "User Added: ",              $F->{added}) ]),
        $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}) ]),
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "MVP Pass: ",                $F->{MVPid}) ]),
        exists $F->{EMTVerified} ? $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "EMT Verified: ",                $F->{EMTVerified}) ]) : "",
        @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}) ])
      ])
    ])
  ]);
  print $h->div ({ class=>"index" }, [$h->p ({ class=>"heading" }, "Schedule:"), getSchedule ($RCID, "all")]) unless $RCID !~ /^\d+$/;
  print $h->div ({ class=>"index" }, [$h->p ({ class=>"heading" }, "Recent Activity:"), getLog ($RCID)]) unless $RCID !~ /^\d+$/;
  print $h->close ('html');
  exit;
}


sub checkDupes {
  my $field = shift;
  my $nametocheck = shift;
  my $han = $dbh->prepare("select RCid from official where $field = ?");
  $han->execute($nametocheck);
  my ($rcid) = $han->fetchrow();
  return $rcid;
}

sub getLog {
  my $RCID = shift;
  
  my @activity_log;
  my $alog = $dbh->prepare("select timestamp, event from v_log where RCid = ? limit 10");
  $alog->execute($RCID);
  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.pl?filter-RCid=".$RCID }, "[Entire log history]"));
}

sub getDepartmentDescriptions {
  my %HASH;
  my $sth = $dbh->prepare("select TLA, description from department");
  $sth->execute();
  while (my ($tla, $name) = $sth->fetchrow) {
    $HASH{$tla} = $name;
  }
  return \%HASH;  
}

sub getDepartmentLinks {
  my %HASH;
  my $sth = $dbh->prepare("select TLA, link from department where link <> ''");
  $sth->execute();
  while (my ($tla, $name) = $sth->fetchrow) {
    $HASH{$tla} = $name;
  }
  return \%HASH;  
}

sub changeUser {
  my ($uid, $field, $newvalue) = @_;
  
  return "ERROR: Bad (or missing) RCid: [$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 RCid" if $field eq "RCid";
  
  if ($field eq "password") {
    return unless $newvalue;
    $dbh->do ("update official set password = password(?) where RCid = ?", undef, $newvalue, $uid) or return "ERROR: ".$dbh->errstr;
  } else {
    $dbh->do ("update official set $field = ? where RCid = ?", undef, $newvalue, $uid) or return "ERROR: ".$dbh->errstr;
  }
  
  $newvalue = '********' if $field eq "password";
  if ($ORCUSER->{RCid} eq $uid) {
    logit ($uid, "Updated Profile: $field -> $newvalue");
  } else {
    logit ($ORCUSER->{RCid}, "Updated User [$uid]: $field -> $newvalue");
    logit ($uid, "$ORCUSER->{derby_name} updated your profile: $field -> $newvalue");
  }
  
  return;
}