Subversion Repositories VORC

Rev

Rev 58 | 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 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 $dbh = WebDB->connect ();
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");

# 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->{'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->{level}       = param ('level')      // '';
#       $F->{type}        = param ('type')       // '';
        $F->{RCid}        = param ('RCid')       // '';
        $F->{access}      = param ('access')     // 0;
        $F->{mvp_pass}    = defined param ('mvp_pass') ? 1 : 0;
        $F->{department}  = join ":", map { "$_-".param ("DEPT-".$_) } map { s/^DEPT-//; $_ } grep { param ($_) ne "" } grep { /^DEPT-/ } param ;
  my @AUTODEPTS = map { $_->[0] } $dbh->selectall_array ("select TLA from department where autoapprove = true");
  
  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 Real 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->{level})      { $F->{level} = "B"; } # People keep leaving level blank.  Default 'em if they do.
#               if (!$F->{type})       { $F->{type} = "official"; } # and now they left the other drop-down blank!!!
                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 (!$F->{department}) { push @ERRORS, "You need to request at least one Department!"; }
    
                if (scalar @ERRORS) {
                        $ERRMSG = join $h->br, @ERRORS;
                        display_form ("New", "New User", $ERRMSG, $F);
                        return;
                } 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};
                        use tableViewer;
                        map { $F->{department}->{$_} = inArray ($_, \@AUTODEPTS) } keys %{$F->{department}};
                        $F->{department} = convertDepartments $F->{department};
                        
#                       my $sth = $dbh->prepare ("insert into official (email, password, derby_name, real_name, phone, level, type, access, department, clinic_pass) values (?, password(?), ?, ?, ?, ?, ?, ?, ?, ?)");
                        my $sth = $dbh->prepare ("insert into official (email, password, derby_name, real_name, pronouns, tshirt, phone, timeformat, access, department, added, activation) values (?, password(?), ?, ?, ?, ?, ?, ?, ?, ?, CONVERT_TZ(now(), 'America/Chicago', 'America/Los_Angeles'), md5(rand()))");

#                       $sth->execute ($F->{email}, $F->{password}, $F->{derby_name}, $F->{real_name}, $F->{phone}, $F->{level}, $F->{type}, 0, $F->{department}, 0);
                        $sth->execute ($F->{email}, $F->{password}, $F->{derby_name}, $F->{real_name}, $F->{pronouns}, $F->{tshirt}, $F->{phone}, $F->{timeformat}, 0, $F->{department});

                        $sth = $dbh->prepare ("select RCid, activation from official where email = ?");
                        $sth->execute ($F->{email});
                        ($F->{RCid}, $F->{activation}) = $sth->fetchrow_array;
                        logit ($F->{RCid}, "New User Registration");
                        sendNewUserEMail ("New User", $F);
                        $cookie_string = authenticate (1);
                }
        } else {
                $cookie_string = authenticate (1);
                my ($EM, $PWD, $AL) = split /&/, $cookie_string;
                if (lc $EM eq lc $F->{email} and $AL < 5) { # They're editing their own record (and not a sysadmin).
      
                        # Don't let users change their own mvp_pass setting...
                  $F->{mvp_pass} = getUser($EM)->{mvp_pass};
                        my $DBDepts = getUser($EM)->{department};
                  if ($F->{department} ne $DBDepts) {
                        # 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.
        use tableViewer;
                        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;
                  }

      if ($F->{password}) { # They've possibly included an updated password.
#               my $sth = $dbh->prepare("replace into official (RCid, email, password, derby_name, real_name, phone, level, type, access, department, clinic_pass) values (?, ?, password(?), ?, ?, ?, ?, ?, ?, ?, ?)");
#               $sth->execute ($F->{RCid}, $EM, $F->{password}, $F->{derby_name}, $F->{real_name}, $F->{phone}, $F->{level}, $F->{type}, $F->{access}, $F->{department}, $F->{clinic_pass})
                my $sth = $dbh->prepare("replace into official (RCid, email, password, derby_name, real_name, pronouns, tshirt, phone, activation, timeformat, access, mvp_pass, department, added, last_login) values (?, ?, password(?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $sth->execute ($F->{RCid}, lc $EM, $F->{password}, $F->{derby_name}, $F->{real_name}, $F->{pronouns}, $F->{tshirt}, $F->{phone}, getUser($EM)->{activation}, $F->{timeformat}, $F->{access}, $F->{mvp_pass}, $F->{department}, getUser($EM)->{added}, getUser($EM)->{last_login})
                        or $ERRMSG = "ERROR: Can't execute SQL statement: ".$sth->errstr()."\n";
        } else { # No password was included, just keep the existing one.
#               my $sth = $dbh->prepare("replace into official (RCid, email, password, derby_name, real_name, phone, level, type, access, department, clinic_pass) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
#               $sth->execute($F->{RCid}, $EM, $PWD, $F->{derby_name}, $F->{real_name}, $F->{phone}, $F->{level}, $F->{type}, $F->{access}, $F->{department}, $F->{clinic_pass})
                my $sth = $dbh->prepare("replace into official (RCid, email, password, derby_name, real_name, pronouns, tshirt, phone, activation, timeformat, access, mvp_pass, department, added, last_login) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $sth->execute($F->{RCid}, lc $EM, $PWD, $F->{derby_name}, $F->{real_name}, $F->{pronouns}, $F->{tshirt}, $F->{phone}, getUser($EM)->{activation}, $F->{timeformat}, $F->{access}, $F->{mvp_pass}, $F->{department}, getUser($EM)->{added}, getUser($EM)->{last_login})
                        or $ERRMSG = "ERROR: Can't execute SQL statement: ".$sth->errstr()."\n";
        }

                        if ($ERRMSG) {
                                logit ($F->{RCid}, "DB ERROR: Updating Self Details: $ERRMSG");
                        } else {
                                logit ($F->{RCid}, "Updated User Details");
                        }
                } elsif ($AL > 1) { # A lead or higher is updating someone else's record
                  
                  use List::Util qw/sum/;
#                 if (sum (values %{ convertDepartments ($F->{department}) }) > 0 and $F->{access} == 0) {
                  if (sum (values %{ convertDepartments ($F->{department}) }) > 0 and $F->{access} == 1) {
                    # activating a user for the first time...
                    $F->{access} = 1;
#                   sendNewUserEMail ("Activate", $F);
                  }
                  
                        if ($FORM->{password}) {
#                               my $sth = $dbh->prepare ("replace into official (RCid, email, password, derby_name, real_name, phone, level, type, access, department, clinic_pass) values (?, ?, password(?), ?, ?, ?, ?, ?, ?, ?, ?)");
#                               $sth->execute ($F->{RCid}, $F->{email}, $F->{password}, $F->{derby_name}, $F->{real_name}, $F->{phone}, $F->{level}, $F->{type}, $F->{access}, $F->{department}, $F->{clinic_pass})
                                my $sth = $dbh->prepare ("replace into official (RCid, email, password, derby_name, real_name, pronouns, tshirt, phone, activation, timeformat, access, mvp_pass, department, added, last_login) values (?, ?, password(?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                                $sth->execute ($F->{RCid}, $F->{email}, $F->{password}, $F->{derby_name}, $F->{real_name}, $F->{pronouns}, $F->{tshirt}, $F->{phone}, getUser($F->{email})->{activation}, $F->{timeformat}, $F->{access}, $F->{mvp_pass}, $F->{department}, getUser($F->{email})->{added}, getUser($F->{email})->{last_login})
                                        or $ERRMSG = "ERROR: Can't execute SQL statement: ".$sth->errstr()."\n";
                        } else {
#                               my $sth = $dbh->prepare ("update official set email = ?, derby_name = ?, real_name = ?, phone = ?, level = ?, type = ?, access = ?, department = ?, clinic_pass = ? where RCid = ?");
#                               $sth->execute ($F->{email}, $F->{derby_name}, $F->{real_name}, $F->{phone}, $F->{level}, $F->{type}, $F->{access}, $F->{department}, $F->{clinic_pass}, $F->{RCid})
                                my $sth = $dbh->prepare ("update official set email = ?, derby_name = ?, real_name = ?, pronouns = ?, tshirt = ?, phone = ?, timeformat = ?, access = ?, mvp_pass = ?, department = ? where RCid = ?");
                                $sth->execute ($F->{email}, $F->{derby_name}, $F->{real_name}, $F->{pronouns}, $F->{tshirt}, $F->{phone}, $F->{timeformat}, $F->{access}, $F->{mvp_pass}, $F->{department}, $F->{RCid})
                                        or $ERRMSG = "ERROR: Can't execute SQL statement: ".$sth->errstr()."\n";
                        }
                        if ($ERRMSG) {
                                logit ($F->{RCid}, "DB ERROR: Updating Someone Else: $ERRMSG");
                        } else {
                                logit ($F->{RCid}, "Updated User Details (by ".getUser($EM)->{derby_name}.")");
                                logit (getUser($EM)->{RCid}, "Updated User Details: ".$F->{derby_name}." (".$F->{RCid}.")");
                        }
                } else {
                        $ERRMSG = "Attempting to update someone else's record, and you don't have permission to do that.";
                        logit ($F->{RCid}, "FAIL: ($EM) doesn't have access to update ($F->{email})'s record");
                }
        }
        $F->{password} = "*******";
        $F->{buttons}           = $h->input ({ type=>"hidden", name=>"RCid", value=>$F->{RCid} }).$h->input ({ type=>"submit", name=>"submit", value=>"Edit" });
        if ($F->{mvp_pass}) {
                $F->{mvp_pass}  = $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>"mvp_pass", value=>1, readonly=>[], disabled=>[], checked=>[] }), $h->span ({ class=>"slider round" })]);
        } else {
                $F->{mvp_pass}  = $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>"mvp_pass", value=>0, readonly=>[], disabled=>[] }), $h->span ({ class=>"slider round" })]);
        }
        $F->{department} = convertDepartments ($F->{department});

        display_form ($F->{RCid}, "View");
}

sub display_form {
  my $RCID = shift // "";
  my $view = shift; # // "New User";
  my $errors = shift // "";
  my $F = shift; # // "";
  
  if ($view eq 'Edit') {
        $cookie_string = authenticate (1);
        my ($EM, $PWD, $AL) = split /&/, $cookie_string;
        $F = getUser ($RCID);
        my $currentuser = getUser ($EM);
#       $currentuser->{department} = convertDepartments ($currentuser->{department});
        
#       if (lc $EM eq lc $F->{email} or $AL > 1) {
        if (canView ($currentuser, $F)) {
          # Editing your own record OR you're a lead/higher
                if (lc $EM eq lc $F->{email} or $currentuser->{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..$currentuser->{access})]);
                }
                if ($currentuser->{access} > 2) {  #this would be the place to test for other types of managers that can update the MVP Pass setting
                                if ($F->{mvp_pass}) {
                                        $F->{mvp_pass}  = $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>"mvp_pass", value=>1, checked=>[] }), $h->span ({ class=>"slider round" })]);
                                } else {
                                        $F->{mvp_pass}  = $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>"mvp_pass", value=>0 }), $h->span ({ class=>"slider round" })]);
                                }
                } else {
                                if ($F->{mvp_pass}) {
                                        $F->{mvp_pass}  = $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>"mvp_pass", value=>1, readonly=>[], disabled=>[], checked=>[] }), $h->span ({ class=>"slider round" })]);
                                } else {
                                        $F->{mvp_pass}  = $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>"mvp_pass", value=>0, readonly=>[], disabled=>[] }), $h->span ({ class=>"slider round" })]);
                                }
                }
      if ($AL == 5) {
          $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 ($currentuser->{RCid} eq $F->{RCid} or $currentuser->{access} > 4) {
                        $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)] );
                } else {
                        $F->{password}   = '*******';
                }
#               $F->{level}      = "<SELECT NAME=level>".selectOptions ($F->{level}, [qw(AA A B C)])."</SELECT>";
#               $F->{type}       = "<SELECT NAME=type>".selectOptions ($F->{type}, [qw(official nso referee)])."</SELECT>";
                $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});
        $currentuser->{department} = convertDepartments ($currentuser->{department});
        foreach my $k (keys %{$depts}) {
          next if $k eq "CMP";
          if ($currentuser->{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 ($currentuser->{department}->{$k} > 1 and $currentuser->{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..$currentuser->{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" })]);
          } 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 sign-up for things until your account has been reviewed and approved. Watch your email for notification.";
        # 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)] );
#       $F->{level}      = "<SELECT NAME=level>".selectOptions ($F->{level}, ["", qw(AA A B C)])."</SELECT>";
#       $F->{type}       = "<SELECT NAME=type>".selectOptions ($F->{type}, ["", qw(official nso referee)])."</SELECT>";
                $F->{RCid}         = $h->input ({ type=>"hidden", name=>"RCid", value=>"New" })."TBD&nbsp;";
        $F->{access}                    = $h->input ({ type=>"hidden", name=>"access", value=>0 })."0";
        $F->{mvp_pass}   = $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>"mvp_pass", value=>0, readonly=>[], disabled=>[] }), $h->span ({ class=>"slider round" })]);
    
    $F->{department} = convertDepartments ($F->{department});
        foreach (sort keys %{$depts}) {
          next if $_ eq "CMP";
          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 $currentuser = getUser ($EM);
    my  $targetuser = getUser ($RCID);

        if (canView ($currentuser, $targetuser)) {
        $F = $targetuser;
        $F->{department} = convertDepartments ($F->{department});
      $F->{access} = $AccessLevel->{$F->{access}};
        $F->{'password'} = "*******";
      $F->{buttons}             = $h->input ({ type=>"hidden", name=>"RCid", value=>$F->{'RCid'} }).$h->input ({ type=>"submit", name=>"submit", value=>"Edit" });
                        if ($F->{mvp_pass}) {
                                $F->{mvp_pass}  = $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>"mvp_pass", value=>1, readonly=>[], disabled=>[], checked=>[] }), $h->span ({ class=>"slider round" })]);
                        } else {
                                $F->{mvp_pass}  = $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>"mvp_pass", value=>0, readonly=>[], disabled=>[] }), $h->span ({ class=>"slider round" })]);
                        }
        } else {
          logit ($currentuser->{RCid}, "SECURITY: $currentuser->{derby_name} attempted to view another user's ($RCID) info");
          $errors = "Unauthorized attempt to view another user.  This has been logged.";
        $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->{level}      = "&nbsp;";
#       $F->{type}       = "&nbsp;";
        $F->{RCid}       = "&nbsp;";
        $F->{access}             = "&nbsp;";
        $F->{mvp_pass}   = "&nbsp;";
        $F->{buttons}            = "&nbsp;";
    }

#       if (lc $EM eq lc $F->{email} or $AL > 1) {
#      $F->{buttons}            = $h->input ({ type=>"hidden", name=>"RCid", value=>$F->{'RCid'} }).$h->input ({ type=>"submit", name=>"submit", value=>"Edit" });
#       } else {
#               $F->{buttons} = "";
#       }
  } #else {
  #     $cookie_string = authenticate(1);
  #     $FORM->{email}      = "&nbsp;";
  #     $FORM->{password}   = "&nbsp;";
  #     $FORM->{derby_name} = "&nbsp;";
  #     $FORM->{real_name}  = "&nbsp;";
  #     $FORM->{phone}      = "&nbsp;";
  #     $FORM->{level}      = "&nbsp;";
  #     $FORM->{type}       = "&nbsp;";
  #     $FORM->{RCid}         = "&nbsp;";
  #     $FORM->{access}                 = "&nbsp;";
  #     $FORM->{mvp_pass}       = "&nbsp;";
  #     $FORM->{buttons}                = "&nbsp;";
  #}

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

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

  print header (-cookie=>$RCAUTH_cookie);

  #foreach (keys %ENV) {
  #     print "$_: $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" }, "Department Access:")) );
#  push @printDepartments, $h->div ({ class=>"rTableRow" }, $h->div ({ class=>"rTableCellr hint", style=>"display:block;" }, "Here is where you're signed up to volunteer at RollerCon:"));
  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:")) ]);
#  push @printDepartments, $h->div ({ class=>"hint", style=>"display: unset;" }, "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;" }, "Real 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;" }, "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->{mvp_pass}) ]),
        @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->close('form');
  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');
}

#sub selectOptions {
#       my $selectedOption = shift;
#       my $options = shift;
#       return join " ", map { $selectedOption eq $_ ?
#                               $h->option ({ value=>$_, selected=>[] }, $_) :
#                                                                                                       $h->option ({ value=>$_ }, $_)
#                                                                                       } @$options;
#}


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;  
}