Subversion Repositories PEEPS

Rev

Rev 3 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 - 1
#!/usr/bin/perl
2
 
3
# Redirect error messages to a log of my choosing. (it's annoying to filter for errors in the shared env)
4
#my $error_log_path = $ENV{SERVER_NAME} eq "volunteers.rollercon.com" ? "/home3/rollerco/logs/" : "/tmp/";
5
#close STDERR;
6
#open STDERR, '>>', $error_log_path.'vorc_error.log' or warn "Failed to open redirected logfile ($0): $!";
7
#warn "Redirecting errors to ${error_log_path}vorc_error.log";
8
 
9
use strict;
10
use PEEPS;
11
use tableViewer qw/inArray notInArray/;
12
use CGI qw/param cookie header start_html url url_param/;
13
use Email::Valid;
14
use WebDB;
15
use HTML::Tiny;
16
use Data::Dumper;
17
our $h = HTML::Tiny->new( mode => 'html' );
18
 
19
my ($FORM, $cookie_string, $ERRMSG);
20
my @ERRORS;
21
my $dbh = getDBConnection ();
22
my @FIELDS = qw/ username derby_name derby_short_name email name_first name_middle name_last password active pronouns birthdate /;
23
my @PRIVFIELDS = qw/ email active /;
24
 
25
 
26
# The page's form might be submitted as a POST or a GET (or both?)
27
#  The initial _view_ likely comes as a GET request (making it easier to embed in an HREF as a URL)
28
#  Unpack any values sent in the GET and add them to the FORM hash
29
$FORM->{'SUB'} = WebDB::trim scalar param ('submit') // '';
30
$FORM->{'person_id'} = WebDB::trim scalar param ('person_id'); $FORM->{'person_id'} //= WebDB::trim scalar url_param ('person_id');
31
$FORM->{referer} = WebDB::trim scalar param ("referer") // "";
32
if ($FORM->{'SUB'} eq '') {
33
  if ($ENV{'REQUEST_URI'}) {
34
    my ($g, $keep) = split /\?/, $ENV{'REQUEST_URI'};
35
    if ($keep) {
36
      foreach (split /&/, $keep) {
37
        my ($k, $v) = split /=/;
38
        $k =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
39
        $v =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
40
        $k eq "submit" ? $FORM->{'SUB'} = $v : $FORM->{$k} = $v;
41
      }
42
    }
43
  }
44
}
45
 
46
# Keep track of the original referrer for the 'back' link/button
47
my $goback;
48
if ($FORM->{referer}) {
49
  $goback = $FORM->{referer};
50
} else {
51
  $goback = $ENV{HTTP_REFERER};
52
}
53
 
54
if ($FORM->{'SUB'} eq "Save") {
55
  process_form ($FORM);
56
} elsif ($FORM->{'SUB'} eq "New User") {
57
  display_form ("New", "New User"); # blank form
58
} elsif ($FORM->{'person_id'}) {
59
  display_form ($FORM->{'person_id'}, $FORM->{'SUB'});
60
} else {
61
  $cookie_string = authenticate (1);
62
  my ($EM, $PWD, $AL) = split /&/, $cookie_string;
63
  display_form (getUser ($EM)->{'person_id'}, "View");
64
}
65
 
66
 
67
sub process_form {
68
  my $F = shift // "";
69
  push @ERRORS, "Tried to save an empty form." and return unless $F;
70
  my $changed_username;
71
 
72
  $F->{username}       = WebDB::trim param ('username')   // '';
73
  $F->{email}       = lc WebDB::trim param ('email')   // '';
74
  $F->{password}    = WebDB::trim param ('password')   // '';
75
  $F->{derby_name}  = WebDB::trim param ('derby_name') // '';
76
  $F->{derby_short_name}  = WebDB::trim param ('derby_short_name') // '';
77
  $F->{name_first}   = WebDB::trim param ('name_first')  // '';
78
  $F->{name_middle}   = WebDB::trim param ('name_middle')  // '';
79
  $F->{name_last}   = WebDB::trim param ('name_last')  // '';
80
  $F->{pronouns}    = WebDB::trim param ('pronouns')   // '';
81
  $F->{birthdate}      = WebDB::trim param ('birthdate')     // '';
82
  $F->{person_id}        = param ('person_id')       // '';
83
  $F->{newaffiliation}   =  scalar param ('newaffiliation');
84
  $F->{deleteaffiliation}   = scalar param ('deleteaffiliation');
85
 
86
  if (defined $F->{newaffiliation}) { $F->{newaffiliation} = WebDB::trim $F->{newaffiliation}; } else { delete $F->{newaffiliation} };
87
  if (defined $F->{deleteaffiliation}) { $F->{deleteaffiliation} = WebDB::trim $F->{deleteaffiliation}; } else { delete $F->{deleteaffiliation} };
88
 
89
  if ($F->{person_id} eq "New") {
90
  # Saving a new User...
91
    # But first let's do some error checking...0
92
    my $warn_recovery = "Do you want to ".$h->a ({ href=>"recoverAccount"}, "Recover Your Account")." instead?";
93
    if (!$F->{username})  { push @ERRORS, "Blank Username!"; }
94
    if (checkDupes ('username', 'authentication', $F->{username})) { push @ERRORS, "Username already in use. ".$warn_recovery; $F->{username} = ""; }
95
    if (!$F->{password})   { push @ERRORS, "Blank Password!"; }
96
    if (!$F->{name_first})  { push @ERRORS, "Blank First Name!"; }
97
    if (!$F->{name_last})  { push @ERRORS, "Blank Last Name!"; }
98
#    if (!$F->{derby_name}) { $F->{derby_name} = $F->{real_name}; } # If they leave derby_name blank, use their real_name
99
#    if (checkDupes ('derby_name', $F->{derby_name})) { push @ERRORS, "Derby Name already in use. Pick a different one."; $F->{derby_name} = ""; }
100
    if (!$F->{email})      { push @ERRORS, "Blank Email!"; } else {
101
      $F->{email} =~ s/\s+//g; # make sure people aren't accidentally including spaces
102
      $F->{email} = lc $F->{email}; # sometimes people capitalize their email addresses and that's annoying...
103
      if (! Email::Valid->address (-address => $F->{email}, -mxcheck => 1, -tldcheck => 1)) { push @ERRORS, "Mal-formatted (or fake) Email Address!"; $F->{email} = ""; }
104
    }
105
    if (checkDupes ('email', 'person', $F->{email})) { push @ERRORS, "Email Address already in use. ".$warn_recovery; $F->{email} = ""; }
106
 
107
    if (scalar @ERRORS) {
108
      $ERRMSG = join $h->br, @ERRORS;
109
      display_form ("New", "New User", $ERRMSG, $F);
110
    } else {
111
      # We have a correctly formatted email address with a mail host record, go ahead and add the user
112
 
113
      $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,
114
                                  $F->{email}, $F->{derby_name}, $F->{derby_short_name}, $F->{name_first}, $F->{name_middle}, $F->{name_last}, $F->{pronouns}, $F->{birthdate})
115
        or display_form ("New", "New User", "ERROR: DB: ".$dbh->errstr, $F);
116
 
117
      ($F->{person_id}) = $dbh->selectrow_array ("select id from person where email = ?", undef, $F->{email});
118
      $dbh->do ("insert into authentication (person_id, username, password, activation) values (?, ?, password(?), md5(rand()))", undef, $F->{person_id}, $F->{username}, $F->{password});
119
      ($F->{activation}) = $dbh->selectrow_array ("select activation from authentication where person_id = ?", undef, $F->{person_id});
120
 
121
      $dbh->do ("replace into full_person select * from v_person where id = ?", undef, $F->{person_id});
122
 
123
      logit ($F->{person_id}, "New User Registration");
124
      sendNewUserEMail ("New User", $F);
125
      $cookie_string = authenticate (PEEPS::USER);
126
    }
127
  } else {
128
  # Save changes to an existing user.
129
    $cookie_string = authenticate (PEEPS::USER);
130
    my ($EM, $PWD, $AL) = split /&/, $cookie_string;
131
 
132
    my $OG = getUser ($F->{person_id});
133
 
134
#    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} = ""; }
135
#    if (!$F->{derby_name}) { push @ERRORS, "Blank Derby Name!"; }
136
    if (exists $F->{newaffiliation}) {
137
      push @ERRORS, "No League Selected." unless $F->{newaffiliation};
138
      push @ERRORS, "That's not a Member Org ID [$F->{newaffiliation}]!" if ($F->{newaffiliation} and $F->{newaffiliation} !~ /^\d+$/);
139
      push @ERRORS, "Already a member of ".getLeagueName ($F->{newaffiliation}) unless notInArray ($F->{newaffiliation}, [keys %{getLeagueAffiliation ($F->{person_id})}]);
140
    } elsif (exists $F->{deleteaffiliation}) {
141
      push @ERRORS, "No League Selected." unless $F->{deleteaffiliation};
142
      push @ERRORS, "That's not a Member Org ID [$F->{deleteaffiliation}]!" if ($F->{deleteaffiliation} and $F->{deleteaffiliation} !~ /^\d+$/);
143
      push @ERRORS, "Not a member of ".getLeagueName ($F->{deleteaffiliation}) if ($F->{deleteaffiliation} and notInArray ($F->{deleteaffiliation}, [keys %{getLeagueAffiliation ($F->{person_id})}]));
144
    } else {
145
      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} = ""; }
146
      if (!$F->{name_last})  { push @ERRORS, "Blank Last Name!"; }
147
      if (!$F->{name_first})  { push @ERRORS, "Blank First Name!"; }
148
    }
149
 
150
    if (scalar @ERRORS) {
151
      $ERRMSG = $h->br.join $h->br, @ERRORS;
152
      display_form ($F->{person_id}, (exists $F->{newaffiliation} or exists $F->{deleteaffiliation}) ? "View" : "Edit", $ERRMSG, $F);
153
    }
154
 
155
 
156
    if ($ORCUSER->{person_id} == $F->{person_id} or $AL >= PEEPS::SYSADMIN) {
157
    # They're editing their own record (or a sysadmin).
158
 
159
      if ($F->{newaffiliation}) {
160
 
161
        # warn "new league_id: ".$F->{newaffiliation};
162
        $dbh->do ("insert into role (member_org_id, person_id, role) values (?, ?, ?)", undef, $F->{newaffiliation}, $F->{person_id}, "Pending");
163
 
164
        if ($dbh->errstr) {
165
          my $dberr = $dbh->errstr;
166
          logit ($F->{person_id}, "DB ERROR ($dberr): Requesting league affiliation to ".getLeagueName ($F->{newaffiliation})." [$F->{newaffiliation}]");
167
          push @ERRORS, $dberr;
168
        } else {
169
          logit ($F->{person_id}, "Request to be added to ".getLeagueName ($F->{newaffiliation})." [$F->{newaffiliation}]");
170
          orglogit ($F->{person_id}, $F->{newaffiliation}, "Requested affiliation.");
171
        }
172
 
173
        $dbh->do ("replace into full_person select * from v_person where id = ? and league_id = ?", undef, $F->{person_id}, $F->{newaffiliation});
174
 
175
      } elsif ($F->{deleteaffiliation}) {
176
        # warn "delete league_id: ".$F->{deleteaffiliation};
177
        $dbh->do ("delete from role where member_org_id = ? and person_id = ?", undef, $F->{deleteaffiliation}, $F->{person_id});
178
 
179
        if ($dbh->errstr) {
180
          my $dberr = $dbh->errstr;
181
          logit ($F->{person_id}, "DB ERROR ($dberr): Deleting league affiliation from ".getLeagueName ($F->{deleteaffiliation})." [$F->{deleteaffiliation}]");
182
          push @ERRORS, $dberr;
183
        } else {
184
          logit ($F->{person_id}, "Deleted Affiliation with ".getLeagueName ($F->{deleteaffiliation})." [$F->{deleteaffiliation}]");
185
          orglogit ($F->{person_id}, $F->{deleteaffiliation}, "Removed affiliation.");
186
        }
187
 
188
        $dbh->do ("delete from full_person where id = ? and league_id = ?", undef, $F->{person_id}, $F->{deleteaffiliation});
189
 
190
 
191
      } else {
192
        foreach my $field (@FIELDS) {
193
          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})) {
194
            # No changes to this field, move on...
195
            next;
196
          }
197
 
198
          if ($AL < PEEPS::SYSADMIN and inArray ($field, \@PRIVFIELDS)) {
199
            push @ERRORS, "ERROR: Only SysAdmins are allowed to change the $field field";
200
            logit ($F->{person_id}, "SECURITY: Only SysAdmins are allowed to change the $field field");
201
            next;
202
          }
203
 
204
          # warn "Changing $field: $F->{$field}";
205
          if (my $err = changeUser ($F->{person_id}, $field, $F->{$field})) {
206
            push @ERRORS, $err;
207
            logit ($F->{person_id}, "DB ERROR: Updating User Details: $err");
208
          }
209
        }
210
      }
211
    } else {
212
      push @ERRORS, "Attempting to update someone else's record, and you don't have permission to do that.";
213
      logit ($ORCUSER->{person_id}, "FAIL: You don't have access to update other people's user record");
214
    }
215
  }
216
  $F->{password} = "*******";
217
  $F->{buttons}   = $h->input ({ type=>"hidden", name=>"person_id", value=>$F->{person_id} }).$h->input ({ type=>"submit", name=>"submit", value=>"Edit" });
218
 
219
  if (scalar @ERRORS) {
220
    $ERRMSG = join ($h->br, @ERRORS);
221
  }
222
 
223
  display_form ($F->{person_id}, "View", $ERRMSG);
224
}
225
 
226
sub display_form {
227
  my $person_id = shift // "";
228
  my $view = shift; # // "New User";
229
  my $errors = shift // "";
230
  my $F = shift; # // "";
231
 
232
  if ($view eq 'Edit') {
233
    $cookie_string = authenticate (PEEPS::USER);
234
    my ($EM, $PWD, $AL) = split /&/, $cookie_string;
235
    $F = getUser ($person_id);
236
 
237
    if (canView ($ORCUSER, $F)) {
238
      # Editing your own record OR you're a lead/higher
239
      if (lc $EM eq lc $F->{email} or $ORCUSER->{access} < $F->{access}) {
240
        # If you're editing your own record, or someone who has higher access than you, make access level read-only
241
        #$F->{access}      = $h->input ({ type=>"hidden", name=>"access", value=>$F->{access} }).$AccessLevel->{$F->{access}};
242
      } else {
243
        #$F->{access}      = $h->select ({ name=>"access" }, [map { $F->{access} == $_ ? $h->option ({ value=>$_, selected=>[] }, $AccessLevel->{$_}) : $h->option ({ value=>$_ }, $AccessLevel->{$_}) } (-1..$ORCUSER->{access})]);
244
      }
245
      if ($AL == PEEPS::SYSADMIN) {
246
      # TBD:  allow users to change their email, but it'll re-initiate account activation...
247
        $F->{email}      = $h->input ({ type=>"text", name=>"email", value=>$F->{email} });
248
      } else {
249
        $F->{email}      = $F->{email}.$h->input ({ type=>"hidden", name=>"email", value=>$F->{email} });
250
      }
251
      if ($ORCUSER->{person_id} eq $F->{person_id} or $ORCUSER->{access} >= PEEPS::SYSADMIN) {
252
        $F->{username} = $h->input ({ type=>"text", name=>"username", value=>$F->{username} });
253
        $F->{password}   = $h->input ({ type=>"password", name=>"password" });
254
        $F->{derby_name} = $h->input ({ type=>"text", name=>"derby_name", value=>$F->{derby_name} });
255
        $F->{derby_short_name} = $h->input ({ type=>"text", name=>"derby_short_name", value=>$F->{derby_short_name} });
256
        $F->{name_first}  = $h->input ({ type=>"text", name=>"name_first", value=>$F->{name_first} });
257
        $F->{name_middle}  = $h->input ({ type=>"text", name=>"name_middle", value=>$F->{name_middle} });
258
        $F->{name_last}  = $h->input ({ type=>"text", name=>"name_last", value=>$F->{name_last} });
259
        $F->{pronouns}   = $h->input ({ type=>"text", name=>"pronouns", value=>$F->{pronouns} });
260
        $F->{birthdate}   = $h->input ({ type=>"date", name=>"birthdate", value=>$F->{birthdate} });
261
#        $F->{tshirt}     = $h->select ({ name=>"tshirt" }, [map { $F->{tshirt} eq $_ ? $h->option ({ selected=>[] }, $_) : $h->option ($_) } @tshirtOptions] );
262
        $F->{timeformat} = $h->select ({ name=>"timeformat" }, [map { $F->{timeformat} eq $_ ? $h->option ({ selected=>[] }, $_) : $h->option ($_) } qw(24hr ampm)] );
263
      } else {
264
        $F->{password}   = '*******';
265
      }
266
      $F->{person_id}       = $h->input ({ type=>"hidden", name=>"person_id", value=>$F->{person_id} })."$F->{person_id}&nbsp;";
267
      $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" });
268
 
269
    } else {
270
      $ERRMSG = "Attempting to update someone else's record, and you don't have permission to do that.";
271
    }
272
 
273
  } elsif ($view eq 'New User') {
274
    $errors .= $h->br."NOTE: You will not be able to login until your account has been activated. Watch your email for further instructions.";
275
    # Skip authentication
276
    $F->{username}   = $h->input ({ type=>"text", name=>"username", value=>$F->{username} });
277
    $F->{email}      = $h->input ({ type=>"text", name=>"email", value=>$F->{email} });
278
    $F->{password}   = $h->input ({ type=>"password", name=>"password" });
279
    $F->{derby_name} = $h->input ({ type=>"text", name=>"derby_name", value=>$F->{derby_name} });
280
    $F->{derby_short_name} = $h->input ({ type=>"text", name=>"derby_short_name", value=>$F->{derby_short_name} });
281
    $F->{name_first}  = $h->input ({ type=>"text", name=>"name_first", value=>$F->{name_first} });
282
    $F->{name_middle}  = $h->input ({ type=>"text", name=>"name_middle", value=>$F->{name_middle} });
283
    $F->{name_last}  = $h->input ({ type=>"text", name=>"name_last", value=>$F->{name_last} });
284
    $F->{pronouns}   = $h->input ({ type=>"text", name=>"pronouns", value=>$F->{pronouns} });
285
    $F->{birthdate}   = $h->input ({ type=>"date", name=>"birthdate", value=>$F->{birthdate} });
286
#    $F->{timeformat} = $h->select ({ name=>"timeformat" }, [map { $F->{timeformat} eq $_ ? $h->option ({ selected=>[] }, $_) : $h->option ($_) } qw(24hr ampm)] );
287
    $F->{person_id}         = $h->input ({ type=>"hidden", name=>"person_id", value=>"New" })."TBD&nbsp;";
288
 
289
    $F->{buttons}   = $h->input ({ type=>"submit", name=>"submit", value=>"Save" })." ".$h->input ({ type=>"reset", value=>"Reset" })." ".$h->input ({ type=>"submit", name=>"submit", value=>"Cancel" });
290
    $cookie_string = '';
291
  } elsif ($view eq 'View' or $view eq 'Cancel' or $view =~ /Affiliation$/ or !$view) {
292
    $cookie_string = authenticate (1);
293
    my ($EM, $PWD, $AL) = split /&/, $cookie_string;
294
 
295
    if (!$view) {
296
      $F->{'person_id'} = getUser ($EM)->{'person_id'};
297
    }
298
 
299
    # Check to make sure they're only looking up their own ID unless they're a lead or higher
300
    my $targetuser = getUser ($person_id);
301
 
302
    if (!$targetuser) {
303
      $errors = "User [$person_id] not found.";
304
      $F->{person_id} = "&nbsp;";
305
    } elsif (canView ($ORCUSER, $targetuser)) {
306
      $F = $targetuser;
307
#      $F->{access} = $AccessLevel->{$F->{access}};
308
      $F->{'password'} = "*******";
309
      ($F->{username}, $F->{last_login}) = $dbh->selectrow_array ("select username, last_login from authentication where person_id = ?", undef, $F->{person_id});
310
 
311
      $F->{buttons}   = $h->input ({ type=>"hidden", name=>"person_id", value=>$F->{'person_id'} }).$h->input ({ type=>"submit", name=>"submit", value=>"Edit" });
312
 
313
    } else {
314
      logit ($ORCUSER->{person_id}, "SECURITY: $ORCUSER->{derby_name} attempted to view another user's ($person_id) info");
315
      $errors = "Unauthorized attempt to view another user.  This has been logged.";
316
      $person_id = "";
317
      $F->{email}       = "&nbsp;";
318
      $F->{password}    = "&nbsp;";
319
      $F->{derby_name}  = "&nbsp;";
320
      $F->{derby_short_name} = "&nbsp;";
321
      $F->{name_first}  = "&nbsp;";
322
      $F->{name_middle} = "&nbsp;";
323
      $F->{name_last}   = "&nbsp;";
324
      $F->{pronouns}    = "&nbsp;";
325
      $F->{birthdate}   = "&nbsp;";
326
      $F->{person_id}   = "&nbsp;";
327
      $F->{buttons}     = "&nbsp;";
328
    }
329
 
330
  }
331
 
332
  #---------------START THE HTML--------------------
333
 
334
  my $PEEPSAUTH_cookie = cookie (-name=>'PEEPSAUTH',-value=>"$cookie_string",-expires=>"+30m");
335
 
336
  print header (-cookie=>$PEEPSAUTH_cookie);
337
 
338
  #foreach (keys %ENV) {
339
  # warn "$_: $ENV{$_}\n<br>";
340
  #}
341
 
342
  if ($errors) {
343
    $errors = $h->div ({ class=>"error" }, $errors);
344
  } else {
345
    $errors = "";
346
  }
347
 
348
  printRCHeader ("User Manager");
349
 
350
  print $errors;
351
  print $h->open ("form", { action=>url, method=>'POST', name=>'UserForm', id=>'UserForm'  });
352
  print $h->input ({ type=>"hidden", name=>"referer", value=>$goback }),
353
    $h->div ({ class=>"index" }, [$h->p ({ class=>"heading" }, "User Details:"),
354
      $h->div ({ class=>"rTable", style=>"min-width: 0%;" },[
355
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Member ID: ",               $F->{person_id}) ]),
356
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Username: ",                $F->{username}) ]),
357
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Email: ",                   $F->{email}) ]),
358
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Password: ",                $F->{password}) ]),
359
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Derby Name: ",              $F->{derby_name}) ]),
360
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Derby Short Name: ",        $F->{derby_short_name}) ]),
361
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "First Name: ",              $F->{name_first}) ]),
362
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Middle Name: ",             $F->{name_middle}) ]),
363
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Last Name: ",               $F->{name_last}) ]),
364
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Pronouns: ",                $F->{pronouns}) ]),
365
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Birthdate: ",               $F->{birthdate}) ]),
366
#        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Time Format: ",       $F->{timeformat}) ]),
367
        $F->{person_id} =~ /^\d+$/ ? $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "User Added: ",              $F->{created}) ]) : "",
368
        $F->{person_id} =~ /^\d+$/ ? $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Last Login: ",              $F->{last_login}) ]) : "",
369
#        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "vORC Access Level: ",       $F->{access}) ]),
370
#        @printDepartments,
371
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCell" }, "&nbsp;") ]),
372
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr" }, $h->a ({ href=>$goback }, "[go back]"), $F->{buttons}) ])
373
      ])
374
    ]);
375
  my $YEAR = 1900 + (localtime)[5];
376
 
377
  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});
378
 
379
  # Display the list of roles per League Affiliation.  If the viewing user is a league (or wftda) admin, include a button to manage roles.
380
  my $leagues = getLeagueAffiliation($person_id);
381
  my @leagueroles;
382
  foreach (sort keys %{$leagues}) {
383
    my ($isALeagueAdmin) = inArray ($_, isLeagueAdmin ($ORCUSER->{person_id}));
384
 
385
    push @leagueroles, $h->div ({ class=>"rTableRow shaded", onClick=>"window.location.href='view_league?id=$_'" },[
386
                         $h->div ({ class=>"rTableCellr".($leagues->{$_}->[0] eq "Pending" ? " highlighted" : ""), style=>"font-size: smaller;".($leagues->{$_}->[0] eq "Pending" ? " font-style: italic;" : "") },
387
                           getLeagueName ($_),
388
                           join ($h->br, sort @{$leagues->{$_}}),
389
                           ($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 ) ]);
390
  }
391
  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) ) ]) );
392
  print $h->ul ([@leagueroles]);
393
 
394
  if ($FORM->{SUB} eq "Request League Affiliation") {
395
    print $h->ul ([
396
      $h->select ({ name => "newaffiliation" }, [$h->option (), map {$h->option ({value=>$_->[0]}, $_->[1])} @{ getLeagues ($person_id) } ] ),
397
      $h->input ( {type=>"submit", name=>"submit", value=>"Save" }).'&nbsp;'.$h->input ({ type=>"submit", name=>"submit", value=>"Cancel" })
398
    ]);
399
  } elsif ($F->{person_id} == $ORCUSER->{person_id}) {
400
    print $h->ul ($h->div ({ class=>"rTableRow" }, $h->input ({ type => "submit", name => "submit", value => "Request League Affiliation", onClick => "document.forms['UserForm'].requestSubmit();" })));
401
  }
402
 
403
  if ($FORM->{SUB} eq "Remove Affiliation") {
404
    print $h->ul ([
405
      $h->select ({ name => "deleteaffiliation", id=>'delaff' }, [$h->option (), map {$h->option ({value=>$_}, getLeagueName ($_))} sort keys %{$leagues} ] ),
406
      $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" })
407
    ]);
408
  } elsif ($F->{person_id} == $ORCUSER->{person_id}) {
409
    print $h->ul ($h->div ({ class=>"rTableRow" }, $h->input ({ type => "submit", name => "submit", value => "Remove Affiliation", onClick => "document.forms['UserForm'].requestSubmit();" })));
410
  }
411
 
412
 
413
  my @policyhistory = ($h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableHead", style=>"font-size: smaller;" }, qw(ID Policy Start End) ) ]));
414
  my @policy_columns = qw(id person_id member_org_id policy_name fee created start end terminated active);
415
 
416
  my @policies = @{ $dbh->selectall_arrayref ("select * from coverage where person_id = ? order by start desc, end", undef, $person_id) };
417
  my $active_policy = isPersonCovered ($person_id);
418
  foreach (@policies) {
419
    my %policy;
420
    @policy{@policy_columns} = @{$_};
421
 
422
    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}) ]);
423
 
424
  #  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}) ]);
425
  }
426
  print $h->ul ([ @policyhistory ]) if (scalar @policies);
427
 
428
#  print $h->div ({ class=>"index" }, [
429
#                      $h->p ({ class=>"heading" }, "League Affiliation:"),
430
#                      $h->ul ({style=>"margin-right: 200px;"}, [
431
#                                map { $h->li ({class=>"shaded"},[
432
#                                                  $h->div ( {class=>"liLeft"}, getLeagueName ($_)),
433
#                                                  $h->div ( {class=>"liRight"}, join (", ", @{$leagues->{$_}}) )
434
#                                              ])
435
#                                    } sort keys %{$leagues}
436
#                              ])
437
#                ]) unless $person_id !~ /^\d+$/;
438
 
439
 
440
  print $h->div ({ class=>"index" }, [$h->p ({ class=>"heading" }, "Recent Activity:"), getLog ($person_id)]) unless $person_id !~ /^\d+$/;
441
  print $h->close ('form', 'body', 'html');
442
  exit;
443
}
444
 
445
 
446
sub checkDupes {
447
  my $field = shift;
448
  my $table = shift;
449
  my $nametocheck = shift;
450
  my $han = $dbh->prepare("select count(*) from $table where $field = ?");
451
  $han->execute($nametocheck);
452
  my ($person_id) = $han->fetchrow();
453
  return $person_id;
454
}
455
 
456
sub getLog {
457
  my $person_id = shift;
458
 
459
  my @activity_log;
460
  my $alog = $dbh->prepare("select timestamp, event from log where person_id = ? order by eventid desc limit 10");
461
  $alog->execute($person_id);
462
  while (my @logs = $alog->fetchrow_array) {
463
    push @activity_log, $h->li ({ class=>"shaded" }, join " ", @logs);
464
  }
465
 
466
  return $h->ul ([@activity_log]).$h->h5 ($h->a ({ href=>"log?filter-person_id=".$person_id }, "[Entire log history]"));
467
}
468
 
469
sub changeUser {
470
  my ($uid, $field, $newvalue) = @_;
471
 
472
  return "ERROR: Bad (or missing) person_id: [$uid]" unless $uid =~ /^\d+$/;
473
  return "ERROR: Bad (or missing) field name: [$field]" unless $field;
474
#  return "ERROR: Bad (or missing) new value: [$newvalue]" unless $newvalue;
475
  return "ERROR: Can't change someone's person_id" if $field eq "person_id";
476
 
477
  if ($field eq "password") {
478
    return unless $newvalue;
479
    $dbh->do ("update authentication set password = password(?) where person_id = ?", undef, $newvalue, $uid) or return "ERROR: ".$dbh->errstr;
480
  } else {
481
    my $table = ($field eq "username") ? "authentication" : "person";
482
    my $id    = ($field eq "username") ? "person_id" : "id";
483
    $dbh->do ("update $table set $field = ? where $id = ?", undef, $newvalue, $uid) or return "ERROR: ".$dbh->errstr;
484
    $dbh->do ("replace into full_person select * from v_person where id = ?", undef, $uid);
485
  }
486
 
487
  $newvalue = '********' if $field eq "password";
488
  if ($ORCUSER->{person_id} eq $uid) {
489
    logit ($uid, "Updated Profile: $field -> $newvalue");
490
  } else {
491
    logit ($ORCUSER->{person_id}, "Updated User [$uid]: $field -> $newvalue");
492
    logit ($uid, "$ORCUSER->{derby_name} updated your profile: $field -> $newvalue");
493
  }
494
 
495
  return;
496
}