Subversion Repositories PEEPS

Rev

Rev 17 | Rev 20 | 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.");
19 - 172
          PEEPSMailer::emailAffiliationRequest ($F->{person_id}, $F->{newaffiliation});
2 - 173
        }
174
 
175
        $dbh->do ("replace into full_person select * from v_person where id = ? and league_id = ?", undef, $F->{person_id}, $F->{newaffiliation});
176
 
177
      } elsif ($F->{deleteaffiliation}) {
178
        # warn "delete league_id: ".$F->{deleteaffiliation};
179
        $dbh->do ("delete from role where member_org_id = ? and person_id = ?", undef, $F->{deleteaffiliation}, $F->{person_id});
180
 
181
        if ($dbh->errstr) {
182
          my $dberr = $dbh->errstr;
183
          logit ($F->{person_id}, "DB ERROR ($dberr): Deleting league affiliation from ".getLeagueName ($F->{deleteaffiliation})." [$F->{deleteaffiliation}]");
184
          push @ERRORS, $dberr;
185
        } else {
186
          logit ($F->{person_id}, "Deleted Affiliation with ".getLeagueName ($F->{deleteaffiliation})." [$F->{deleteaffiliation}]");
187
          orglogit ($F->{person_id}, $F->{deleteaffiliation}, "Removed affiliation.");
19 - 188
          PEEPSMailer::emailAffiliationRemoved ($F->{person_id}, $F->{deleteaffiliation});
2 - 189
        }
190
 
191
        $dbh->do ("delete from full_person where id = ? and league_id = ?", undef, $F->{person_id}, $F->{deleteaffiliation});
192
 
193
 
194
      } else {
195
        foreach my $field (@FIELDS) {
196
          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})) {
197
            # No changes to this field, move on...
198
            next;
199
          }
200
 
201
          if ($AL < PEEPS::SYSADMIN and inArray ($field, \@PRIVFIELDS)) {
202
            push @ERRORS, "ERROR: Only SysAdmins are allowed to change the $field field";
203
            logit ($F->{person_id}, "SECURITY: Only SysAdmins are allowed to change the $field field");
204
            next;
205
          }
206
 
207
          # warn "Changing $field: $F->{$field}";
208
          if (my $err = changeUser ($F->{person_id}, $field, $F->{$field})) {
209
            push @ERRORS, $err;
210
            logit ($F->{person_id}, "DB ERROR: Updating User Details: $err");
211
          }
212
        }
213
      }
214
    } else {
215
      push @ERRORS, "Attempting to update someone else's record, and you don't have permission to do that.";
216
      logit ($ORCUSER->{person_id}, "FAIL: You don't have access to update other people's user record");
217
    }
218
  }
219
  $F->{password} = "*******";
220
  $F->{buttons}   = $h->input ({ type=>"hidden", name=>"person_id", value=>$F->{person_id} }).$h->input ({ type=>"submit", name=>"submit", value=>"Edit" });
221
 
222
  if (scalar @ERRORS) {
223
    $ERRMSG = join ($h->br, @ERRORS);
224
  }
225
 
226
  display_form ($F->{person_id}, "View", $ERRMSG);
227
}
228
 
229
sub display_form {
230
  my $person_id = shift // "";
231
  my $view = shift; # // "New User";
232
  my $errors = shift // "";
233
  my $F = shift; # // "";
234
 
235
  if ($view eq 'Edit') {
236
    $cookie_string = authenticate (PEEPS::USER);
237
    my ($EM, $PWD, $AL) = split /&/, $cookie_string;
238
    $F = getUser ($person_id);
239
 
240
    if (canView ($ORCUSER, $F)) {
241
      # Editing your own record OR you're a lead/higher
242
      if (lc $EM eq lc $F->{email} or $ORCUSER->{access} < $F->{access}) {
243
        # If you're editing your own record, or someone who has higher access than you, make access level read-only
244
        #$F->{access}      = $h->input ({ type=>"hidden", name=>"access", value=>$F->{access} }).$AccessLevel->{$F->{access}};
245
      } else {
246
        #$F->{access}      = $h->select ({ name=>"access" }, [map { $F->{access} == $_ ? $h->option ({ value=>$_, selected=>[] }, $AccessLevel->{$_}) : $h->option ({ value=>$_ }, $AccessLevel->{$_}) } (-1..$ORCUSER->{access})]);
247
      }
248
      if ($AL == PEEPS::SYSADMIN) {
249
      # TBD:  allow users to change their email, but it'll re-initiate account activation...
250
        $F->{email}      = $h->input ({ type=>"text", name=>"email", value=>$F->{email} });
251
      } else {
252
        $F->{email}      = $F->{email}.$h->input ({ type=>"hidden", name=>"email", value=>$F->{email} });
253
      }
254
      if ($ORCUSER->{person_id} eq $F->{person_id} or $ORCUSER->{access} >= PEEPS::SYSADMIN) {
255
        $F->{username} = $h->input ({ type=>"text", name=>"username", value=>$F->{username} });
256
        $F->{password}   = $h->input ({ type=>"password", name=>"password" });
257
        $F->{derby_name} = $h->input ({ type=>"text", name=>"derby_name", value=>$F->{derby_name} });
258
        $F->{derby_short_name} = $h->input ({ type=>"text", name=>"derby_short_name", value=>$F->{derby_short_name} });
259
        $F->{name_first}  = $h->input ({ type=>"text", name=>"name_first", value=>$F->{name_first} });
260
        $F->{name_middle}  = $h->input ({ type=>"text", name=>"name_middle", value=>$F->{name_middle} });
261
        $F->{name_last}  = $h->input ({ type=>"text", name=>"name_last", value=>$F->{name_last} });
262
        $F->{pronouns}   = $h->input ({ type=>"text", name=>"pronouns", value=>$F->{pronouns} });
263
        $F->{birthdate}   = $h->input ({ type=>"date", name=>"birthdate", value=>$F->{birthdate} });
264
#        $F->{tshirt}     = $h->select ({ name=>"tshirt" }, [map { $F->{tshirt} eq $_ ? $h->option ({ selected=>[] }, $_) : $h->option ($_) } @tshirtOptions] );
265
        $F->{timeformat} = $h->select ({ name=>"timeformat" }, [map { $F->{timeformat} eq $_ ? $h->option ({ selected=>[] }, $_) : $h->option ($_) } qw(24hr ampm)] );
266
      } else {
267
        $F->{password}   = '*******';
268
      }
269
      $F->{person_id}       = $h->input ({ type=>"hidden", name=>"person_id", value=>$F->{person_id} })."$F->{person_id}&nbsp;";
270
      $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" });
271
 
272
    } else {
273
      $ERRMSG = "Attempting to update someone else's record, and you don't have permission to do that.";
274
    }
275
 
276
  } elsif ($view eq 'New User') {
277
    $errors .= $h->br."NOTE: You will not be able to login until your account has been activated. Watch your email for further instructions.";
278
    # Skip authentication
279
    $F->{username}   = $h->input ({ type=>"text", name=>"username", value=>$F->{username} });
280
    $F->{email}      = $h->input ({ type=>"text", name=>"email", value=>$F->{email} });
281
    $F->{password}   = $h->input ({ type=>"password", name=>"password" });
282
    $F->{derby_name} = $h->input ({ type=>"text", name=>"derby_name", value=>$F->{derby_name} });
283
    $F->{derby_short_name} = $h->input ({ type=>"text", name=>"derby_short_name", value=>$F->{derby_short_name} });
284
    $F->{name_first}  = $h->input ({ type=>"text", name=>"name_first", value=>$F->{name_first} });
285
    $F->{name_middle}  = $h->input ({ type=>"text", name=>"name_middle", value=>$F->{name_middle} });
286
    $F->{name_last}  = $h->input ({ type=>"text", name=>"name_last", value=>$F->{name_last} });
287
    $F->{pronouns}   = $h->input ({ type=>"text", name=>"pronouns", value=>$F->{pronouns} });
288
    $F->{birthdate}   = $h->input ({ type=>"date", name=>"birthdate", value=>$F->{birthdate} });
289
#    $F->{timeformat} = $h->select ({ name=>"timeformat" }, [map { $F->{timeformat} eq $_ ? $h->option ({ selected=>[] }, $_) : $h->option ($_) } qw(24hr ampm)] );
290
    $F->{person_id}         = $h->input ({ type=>"hidden", name=>"person_id", value=>"New" })."TBD&nbsp;";
291
 
292
    $F->{buttons}   = $h->input ({ type=>"submit", name=>"submit", value=>"Save" })." ".$h->input ({ type=>"reset", value=>"Reset" })." ".$h->input ({ type=>"submit", name=>"submit", value=>"Cancel" });
293
    $cookie_string = '';
294
  } elsif ($view eq 'View' or $view eq 'Cancel' or $view =~ /Affiliation$/ or !$view) {
295
    $cookie_string = authenticate (1);
296
    my ($EM, $PWD, $AL) = split /&/, $cookie_string;
297
 
298
    if (!$view) {
299
      $F->{'person_id'} = getUser ($EM)->{'person_id'};
300
    }
301
 
302
    # Check to make sure they're only looking up their own ID unless they're a lead or higher
303
    my $targetuser = getUser ($person_id);
304
 
305
    if (!$targetuser) {
306
      $errors = "User [$person_id] not found.";
307
      $F->{person_id} = "&nbsp;";
308
    } elsif (canView ($ORCUSER, $targetuser)) {
309
      $F = $targetuser;
310
#      $F->{access} = $AccessLevel->{$F->{access}};
311
      $F->{'password'} = "*******";
312
      ($F->{username}, $F->{last_login}) = $dbh->selectrow_array ("select username, last_login from authentication where person_id = ?", undef, $F->{person_id});
313
 
314
      $F->{buttons}   = $h->input ({ type=>"hidden", name=>"person_id", value=>$F->{'person_id'} }).$h->input ({ type=>"submit", name=>"submit", value=>"Edit" });
315
 
316
    } else {
317
      logit ($ORCUSER->{person_id}, "SECURITY: $ORCUSER->{derby_name} attempted to view another user's ($person_id) info");
318
      $errors = "Unauthorized attempt to view another user.  This has been logged.";
319
      $person_id = "";
320
      $F->{email}       = "&nbsp;";
321
      $F->{password}    = "&nbsp;";
322
      $F->{derby_name}  = "&nbsp;";
323
      $F->{derby_short_name} = "&nbsp;";
324
      $F->{name_first}  = "&nbsp;";
325
      $F->{name_middle} = "&nbsp;";
326
      $F->{name_last}   = "&nbsp;";
327
      $F->{pronouns}    = "&nbsp;";
328
      $F->{birthdate}   = "&nbsp;";
329
      $F->{person_id}   = "&nbsp;";
330
      $F->{buttons}     = "&nbsp;";
331
    }
332
 
333
  }
334
 
335
  #---------------START THE HTML--------------------
336
 
337
  my $PEEPSAUTH_cookie = cookie (-name=>'PEEPSAUTH',-value=>"$cookie_string",-expires=>"+30m");
338
 
339
  print header (-cookie=>$PEEPSAUTH_cookie);
340
 
341
  #foreach (keys %ENV) {
342
  # warn "$_: $ENV{$_}\n<br>";
343
  #}
344
 
345
  if ($errors) {
346
    $errors = $h->div ({ class=>"error" }, $errors);
347
  } else {
348
    $errors = "";
349
  }
350
 
351
  printRCHeader ("User Manager");
352
 
353
  print $errors;
354
  print $h->open ("form", { action=>url, method=>'POST', name=>'UserForm', id=>'UserForm'  });
355
  print $h->input ({ type=>"hidden", name=>"referer", value=>$goback }),
356
    $h->div ({ class=>"index" }, [$h->p ({ class=>"heading" }, "User Details:"),
357
      $h->div ({ class=>"rTable", style=>"min-width: 0%;" },[
358
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Member ID: ",               $F->{person_id}) ]),
359
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Username: ",                $F->{username}) ]),
360
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Email: ",                   $F->{email}) ]),
361
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Password: ",                $F->{password}) ]),
362
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Derby Name: ",              $F->{derby_name}) ]),
363
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Derby Short Name: ",        $F->{derby_short_name}) ]),
364
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "First Name: ",              $F->{name_first}) ]),
365
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Middle Name: ",             $F->{name_middle}) ]),
366
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Last Name: ",               $F->{name_last}) ]),
367
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Pronouns: ",                $F->{pronouns}) ]),
368
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Birthdate: ",               $F->{birthdate}) ]),
369
#        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Time Format: ",       $F->{timeformat}) ]),
370
        $F->{person_id} =~ /^\d+$/ ? $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "User Added: ",              $F->{created}) ]) : "",
371
        $F->{person_id} =~ /^\d+$/ ? $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "Last Login: ",              $F->{last_login}) ]) : "",
372
#        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr", style=>"font-size: unset;" }, "vORC Access Level: ",       $F->{access}) ]),
373
#        @printDepartments,
374
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCell" }, "&nbsp;") ]),
12 - 375
        $h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableCellr" }, $h->input ({ type=>"button", onClick=>"window.location.href='$goback'", value=>"Back"}), $F->{buttons}) ])
2 - 376
      ])
377
    ]);
378
  my $YEAR = 1900 + (localtime)[5];
379
 
12 - 380
  # Everything beyond here only applies to an existing user.
381
  return unless $view ne "New User";
382
 
2 - 383
  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});
384
 
385
  # Display the list of roles per League Affiliation.  If the viewing user is a league (or wftda) admin, include a button to manage roles.
386
  my $leagues = getLeagueAffiliation($person_id);
387
  my @leagueroles;
388
  foreach (sort keys %{$leagues}) {
389
    my ($isALeagueAdmin) = inArray ($_, isLeagueAdmin ($ORCUSER->{person_id}));
390
 
391
    push @leagueroles, $h->div ({ class=>"rTableRow shaded", onClick=>"window.location.href='view_league?id=$_'" },[
392
                         $h->div ({ class=>"rTableCellr".($leagues->{$_}->[0] eq "Pending" ? " highlighted" : ""), style=>"font-size: smaller;".($leagues->{$_}->[0] eq "Pending" ? " font-style: italic;" : "") },
393
                           getLeagueName ($_),
394
                           join ($h->br, sort @{$leagues->{$_}}),
395
                           ($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 ) ]);
396
  }
397
  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) ) ]) );
398
  print $h->ul ([@leagueroles]);
399
 
400
  if ($FORM->{SUB} eq "Request League Affiliation") {
401
    print $h->ul ([
402
      $h->select ({ name => "newaffiliation" }, [$h->option (), map {$h->option ({value=>$_->[0]}, $_->[1])} @{ getLeagues ($person_id) } ] ),
403
      $h->input ( {type=>"submit", name=>"submit", value=>"Save" }).'&nbsp;'.$h->input ({ type=>"submit", name=>"submit", value=>"Cancel" })
404
    ]);
405
  } elsif ($F->{person_id} == $ORCUSER->{person_id}) {
406
    print $h->ul ($h->div ({ class=>"rTableRow" }, $h->input ({ type => "submit", name => "submit", value => "Request League Affiliation", onClick => "document.forms['UserForm'].requestSubmit();" })));
407
  }
408
 
409
  if ($FORM->{SUB} eq "Remove Affiliation") {
410
    print $h->ul ([
411
      $h->select ({ name => "deleteaffiliation", id=>'delaff' }, [$h->option (), map {$h->option ({value=>$_}, getLeagueName ($_))} sort keys %{$leagues} ] ),
412
      $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" })
413
    ]);
414
  } elsif ($F->{person_id} == $ORCUSER->{person_id}) {
415
    print $h->ul ($h->div ({ class=>"rTableRow" }, $h->input ({ type => "submit", name => "submit", value => "Remove Affiliation", onClick => "document.forms['UserForm'].requestSubmit();" })));
416
  }
417
 
418
 
419
  my @policyhistory = ($h->div ({ class=>"rTableRow" },[ $h->div ({ class=>"rTableHead", style=>"font-size: smaller;" }, qw(ID Policy Start End) ) ]));
420
  my @policy_columns = qw(id person_id member_org_id policy_name fee created start end terminated active);
421
 
422
  my @policies = @{ $dbh->selectall_arrayref ("select * from coverage where person_id = ? order by start desc, end", undef, $person_id) };
423
  my $active_policy = isPersonCovered ($person_id);
424
  foreach (@policies) {
425
    my %policy;
426
    @policy{@policy_columns} = @{$_};
427
 
428
    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}) ]);
429
 
430
  #  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}) ]);
431
  }
432
  print $h->ul ([ @policyhistory ]) if (scalar @policies);
433
 
434
#  print $h->div ({ class=>"index" }, [
435
#                      $h->p ({ class=>"heading" }, "League Affiliation:"),
436
#                      $h->ul ({style=>"margin-right: 200px;"}, [
437
#                                map { $h->li ({class=>"shaded"},[
438
#                                                  $h->div ( {class=>"liLeft"}, getLeagueName ($_)),
439
#                                                  $h->div ( {class=>"liRight"}, join (", ", @{$leagues->{$_}}) )
440
#                                              ])
441
#                                    } sort keys %{$leagues}
442
#                              ])
443
#                ]) unless $person_id !~ /^\d+$/;
444
 
445
 
446
  print $h->div ({ class=>"index" }, [$h->p ({ class=>"heading" }, "Recent Activity:"), getLog ($person_id)]) unless $person_id !~ /^\d+$/;
447
  print $h->close ('form', 'body', 'html');
448
  exit;
449
}
450
 
451
 
452
sub checkDupes {
453
  my $field = shift;
454
  my $table = shift;
455
  my $nametocheck = shift;
456
  my $han = $dbh->prepare("select count(*) from $table where $field = ?");
457
  $han->execute($nametocheck);
458
  my ($person_id) = $han->fetchrow();
459
  return $person_id;
460
}
461
 
462
sub getLog {
463
  my $person_id = shift;
464
 
465
  my @activity_log;
466
  my $alog = $dbh->prepare("select timestamp, event from log where person_id = ? order by eventid desc limit 10");
467
  $alog->execute($person_id);
468
  while (my @logs = $alog->fetchrow_array) {
469
    push @activity_log, $h->li ({ class=>"shaded" }, join " ", @logs);
470
  }
471
 
472
  return $h->ul ([@activity_log]).$h->h5 ($h->a ({ href=>"log?filter-person_id=".$person_id }, "[Entire log history]"));
473
}
474
 
475
sub changeUser {
476
  my ($uid, $field, $newvalue) = @_;
477
 
478
  return "ERROR: Bad (or missing) person_id: [$uid]" unless $uid =~ /^\d+$/;
479
  return "ERROR: Bad (or missing) field name: [$field]" unless $field;
480
#  return "ERROR: Bad (or missing) new value: [$newvalue]" unless $newvalue;
481
  return "ERROR: Can't change someone's person_id" if $field eq "person_id";
482
 
483
  if ($field eq "password") {
484
    return unless $newvalue;
485
    $dbh->do ("update authentication set password = password(?) where person_id = ?", undef, $newvalue, $uid) or return "ERROR: ".$dbh->errstr;
486
  } else {
487
    my $table = ($field eq "username") ? "authentication" : "person";
488
    my $id    = ($field eq "username") ? "person_id" : "id";
17 - 489
    if ($field eq "birthdate" and $newvalue eq "") { $newvalue = undef; }
2 - 490
    $dbh->do ("update $table set $field = ? where $id = ?", undef, $newvalue, $uid) or return "ERROR: ".$dbh->errstr;
491
    $dbh->do ("replace into full_person select * from v_person where id = ?", undef, $uid);
492
  }
493
 
494
  $newvalue = '********' if $field eq "password";
495
  if ($ORCUSER->{person_id} eq $uid) {
496
    logit ($uid, "Updated Profile: $field -> $newvalue");
497
  } else {
498
    logit ($ORCUSER->{person_id}, "Updated User [$uid]: $field -> $newvalue");
499
    logit ($uid, "$ORCUSER->{derby_name} updated your profile: $field -> $newvalue");
500
  }
501
 
502
  return;
5 - 503
}
19 - 504