Subversion Repositories PEEPS

Rev

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