Subversion Repositories ORC

Rev

Rev 36 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 - 1
## RollerCon support functions...
2
 
3
use strict;
9 - 4
use cPanelUserConfig;
2 - 5
use Exporter;
6
use CGI qw/:standard :netscape/;
7
use CGI::Cookie;
8
use DBI;
7 - 9
use WebDB;
2 - 10
 
7 - 11
 
12
my $dbh = WebDB->connect ();
35 - 13
sub getRCDBH {
14
  return $dbh;
15
}
2 - 16
our $ORCUSER;
7 - 17
use constant {
18
    USER   => 1,
19
    LEAD   => 2,
20
    MANAGER  => 3,
21
    DIRECTOR  => 4,
22
    ADMIN  => 5
23
  };
2 - 24
 
7 - 25
sub getAccessLevels {
26
  my %AccessLevels = (
27
    -1 => "Locked",
28
 
29
    1 => "Volunteer",
30
    2 => "Lead",
31
    3 => "Manager",
32
    4 => "Director",
33
    5 => "SysAdmin"
34
  );
35
  return \%AccessLevels;
36
}
37
 
2 - 38
sub authDB {
39
	my $src = shift;
40
	my $id = shift;
41
	my $pass = shift;
42
	my $level = shift;
43
	my ($result, $encpass);
44
 
45
	my $sth = $dbh->prepare("select * from official where email = ?");
46
	$sth->execute($id);
47
	my $RCDBIDHASH = $sth->fetchrow_hashref();
48
 
49
	if ($src eq "form") {
50
		my $pwdhan = $dbh->prepare("select password(?)");
51
		$pwdhan->execute($pass);
52
		($encpass) = $pwdhan->fetchrow();
53
	} else {
54
		$encpass = $pass;
55
	}
56
 
9 - 57
	my $tempDepartments = convertDepartments ($RCDBIDHASH->{department});
58
	my $MAXACCESS = scalar keys %{ $tempDepartments } ? max ($RCDBIDHASH->{'access'}, values %{ $tempDepartments }) : $RCDBIDHASH->{'access'};
59
 
29 - 60
	if (!$RCDBIDHASH->{'RCid'}) {
61
		$result->{ERRMSG} = "Email Address not found!";
2 - 62
		$result->{cookie_string} = '';
63
		$result->{RCid} = '';
64
		logit(0, "Account not found: $id");
65
		$result->{authenticated} = 'false';
66
	} elsif ($RCDBIDHASH->{'password'} ne $encpass) {
67
		$result->{ERRMSG} = "Incorrect Password!";
68
		$result->{cookie_string} = '';
69
		$result->{RCid} = $RCDBIDHASH->{'RCid'};
70
		logit($RCDBIDHASH->{'RCid'}, "Incorrect Password");
71
		$result->{authenticated} = 'false';
9 - 72
	} elsif ($MAXACCESS < $level) {
7 - 73
	  if (getSetting ("MAINTENANCE")) {
74
	    $result->{ERRMSG} = "MAINTENANCE MODE: Logins are temporarily disabled.";
75
	  } else {
76
		  $result->{ERRMSG} = "Your account either needs to be activated, or doesn't have access to this page!";
77
  		logit($RCDBIDHASH->{'RCid'}, "Insufficient Privileges");
78
		}
2 - 79
		$result->{cookie_string} = "${id}&${encpass}&$RCDBIDHASH->{'access'}";
80
		$result->{RCid} = $RCDBIDHASH->{'RCid'};
81
		$result->{authenticated} = 'false';
82
	} else {
83
		$result->{ERRMSG} = '';
7 - 84
		$RCDBIDHASH->{department} = convertDepartments ($RCDBIDHASH->{department});
85
		$RCDBIDHASH->{'access'} = max ($RCDBIDHASH->{'access'}, values %{$RCDBIDHASH->{department}});
2 - 86
		$result->{cookie_string} = "${id}&${encpass}&$RCDBIDHASH->{'access'}";
87
		$result->{RCid} = $RCDBIDHASH->{'RCid'};
88
		logit($RCDBIDHASH->{'RCid'}, "Logged In") if $src eq "form";
25 - 89
		$dbh->do ("update official set last_login = CONVERT_TZ(now(), 'America/Chicago', 'America/Los_Angeles') where RCid = ?", undef, $RCDBIDHASH->{'RCid'}) if $src eq "form";
2 - 90
		$result->{authenticated} = 'true';
7 - 91
#		my @depts = map { s/-\d// } split /:/, $RCDBIDHASH->{department};
92
#		my @depts = split /:/, $RCDBIDHASH->{department};
93
 
2 - 94
		$ORCUSER=$RCDBIDHASH;
95
	}
96
	return $result;
97
}
98
 
7 - 99
sub max {
100
    my ($max, $next, @vars) = @_;
101
    return $max if not $next;
102
    return max( $max > $next ? $max : $next, @vars );
103
}
104
 
2 - 105
sub authenticate {									# Verifies the user has logged in or puts up a log in screen
7 - 106
	my $MAINTMODE = getSetting ("MAINTENANCE");
107
	my $MINLEVEL = $MAINTMODE ? $MAINTMODE : shift // 1;
108
 
2 - 109
	my ($ERRMSG, $authenticated, %FORM);
110
	my $sth = $dbh->prepare("select * from official where email = '?'");
111
 
112
	my $query = new CGI;
7 - 113
# Check to see if the user has already logged in (there should be cookies with their authentication)?
114
	my $RCAUTH = $query->cookie('RCAUTH');
29 - 115
	$FORM{'ID'} = WebDB::trim $query->param('id') || '';
116
	$FORM{'PASS'} = WebDB::trim $query->param('pass') || '';
2 - 117
	$FORM{'SUB'} = $query->param('login') || '';
118
 
119
	if ($FORM{'SUB'}) {
120
		#a log in form was submited
121
		if ($FORM{'SUB'} eq "Submit") {
122
			$authenticated = authDB('form', $FORM{'ID'}, $FORM{'PASS'}, $MINLEVEL);
123
		} elsif ($FORM{'SUB'} eq "New User") {
124
			# Print the new user form and exit
125
		}
126
	} elsif ($RCAUTH) {
127
		#We have an authenication cookie.  Double-check it
128
		my ($RCID, $RCPASS, $RCLVL) = split /&/, $RCAUTH;
129
		$authenticated = authDB('cookie', $RCID, $RCPASS, $MINLEVEL);
130
	} else {
131
		$authenticated->{authenticated} = 'false';
132
	}
133
 
134
 
135
	if ($authenticated->{authenticated} eq 'true') {
136
		return $authenticated->{cookie_string};
137
	}
138
 
139
 
140
 
141
# If we get here, the user has failed authentication; throw up the log-in screen and die.
142
 
143
	my $RCAUTH_cookie = CGI::Cookie->new(-name=>'RCAUTH',-value=>"",-expires=>"now");
144
 
145
if ($authenticated->{ERRMSG}) {
146
	$authenticated->{ERRMSG} = "<TR><TD colspan=2 align=center><font color=red><b>".$authenticated->{ERRMSG}."</b></font>&nbsp</TD></TR>";
147
	# Log the failed access attempt
148
} else {
149
	$authenticated->{ERRMSG} = "";
150
	# Since there was no ERRMSG, no need to log anything.
151
}
152
 
153
	print header(-cookie=>$RCAUTH_cookie);
154
	printRCHeader("Please Sign In");
155
	print<<authpage;
156
	<form action="$ENV{REQUEST_URI}" method=POST name=Req id=Req>
157
		<TR><TD colspan=2 align=center><b><font size=+2>Please Sign In</font>
7 - 158
		<TABLE>
2 - 159
		</TD></TR>
160
		<TR><TD colspan=2>&nbsp</TD></TR>
161
		$authenticated->{ERRMSG}
162
		<TR>
29 - 163
			<TD align=right><B>Email Address:</TD><TD><INPUT type=text id=login name=id></TD>
2 - 164
		</TR>
165
		<TR>
166
			<TD align=right><B>Password:</TD><TD><INPUT type=password name=pass></TD>
167
		</TR>
168
		<TR><TD></TD><TD><INPUT type=submit name=login value=Submit></TD></TR>
169
		<TR><TD colspan=2 align=center>&nbsp;</TD></TR>
170
		<TR><TD colspan=2 align=center><A HREF="/schedule/manage_user.pl?submit=New%20User">[register as a new user]</A></TD></TR>
171
		<TR><TD colspan=2 align=center><A HREF="/schedule/password_reset.pl">[reset your password]</A></TD></TR>
172
	</TABLE>
173
	</FORM>
174
 
175
	<SCRIPT language="JavaScript">
176
	<!--
7 - 177
	document.getElementById("login").focus();
2 - 178
 
179
	function Login () {
180
		document.getElementById('Req').action = "$ENV{SCRIPT_NAME}";
181
		document.getElementById('Req').submit.click();
182
		return true;
183
	}
184
 
185
 
186
	//-->
187
	</SCRIPT>
188
 
189
authpage
190
 
191
#foreach (keys %ENV) {
192
#	print "$_: $ENV{$_}<br>";
193
#}
194
#	&JScript;
195
	exit;
196
}
197
 
7 - 198
sub getShiftDepartment {
199
  my $shiftID = shift // "";
200
  my $dept;
201
 
202
  if ($shiftID =~ /^\d+$/) {
203
    ($dept) = $dbh->selectrow_array ("select dept from shift where id = ?", undef, $shiftID);
204
  } else {
29 - 205
    my ($id, $role) = split /-/, $shiftID;
30 - 206
    ($dept) = $dbh->selectrow_array ("select distinct department from staff_template where role like ?", undef, $role.'%');
7 - 207
  }
29 - 208
#  } elsif ($shiftID =~ /^\d+-ANN/) {
209
#    $dept = "ANN";
210
#  } else {
211
#    $dept = "OFF";
212
#  }
7 - 213
 
214
  return $dept;
215
}
216
 
217
sub getDepartments {
218
  my $RCid = shift // "";
219
  # If we get an RCid, return the list of departments and levels for that user.
220
  #   Otherwise (no parameter), return the list of departments with their display names.
221
 
222
	if ($RCid) {
223
  	my $sth = $dbh->prepare("select department from official where RCid = ?");
224
  	$sth->execute($RCid);
225
  	my ($dlist) = $sth->fetchrow;
226
  	return convertDepartments ($dlist);
227
	} else {
228
  	my %HASH;
229
  	my $sth = $dbh->prepare("select TLA, name from department");
230
  	$sth->execute();
231
  	while (my ($tla, $name) = $sth->fetchrow) {
232
  	  $HASH{$tla} = $name;
233
    }
234
    return \%HASH;
235
  }
236
 
237
}
238
 
239
sub convertDepartments {
240
  # For the department membership, converts the DB string back and forth to a hashref...
241
  my $input = shift // "";
242
  my $output;
243
 
244
  if (ref $input eq "HASH") {
245
    $output = join ":", map { $_."-".$input->{$_} } sort keys %{$input};
246
  } else {
247
  	foreach (split /:/, $input) {
248
  	  my ($tla, $level) = split /-/;
249
  	  $output->{$tla} = $level;
250
    }
251
  }
252
 
253
  return $output;
254
}
255
 
256
sub getSchedule {
257
  my $RCid = shift // return "ERROR: No RCid provided to getSchedule";
258
  my $filter = shift // "";
259
 
260
  my @whereclause;
46 - 261
  if ($filter eq "all") {
262
  	push @whereclause, "date >= '2022-01-01'";
263
  } else {
264
  	push @whereclause, "date >= date(now())";
265
  }
7 - 266
#  if ($RCid ne $ORCUSER->{RCid}) {
267
#    push @whereclause, "dept != 'PER'";
268
#  }
269
 
270
  use DateTime;
25 - 271
  my $dt = DateTime->today (time_zone => 'America/Los_Angeles');
7 - 272
  $dt =~ s/T00\:00\:00$//;
25 - 273
  my $now = DateTime->now (time_zone => 'America/Los_Angeles');
7 - 274
 
275
 
276
  use HTML::Tiny;
277
  my $h = HTML::Tiny->new( mode => 'html' );
278
 
279
  my $where = scalar @whereclause ? "where ".join " and ", @whereclause : "";
280
  my @shifts;
21 - 281
  my $sth = $dbh->prepare("select * from (select id, date, dayofweek, track as location, time, role, teams, signup, 'OFF' as dept, volhours from v_shift_officiating where RCid = ? union
282
                                          select id, date, dayofweek, track as location, time, role, teams, signup, 'ANN' as dept, volhours from v_shift_announcer where RCid = ? union
283
                                          select id, date, dayofweek, location, time, role, '' as teams, type as signup, dept, volhours from v_shift where RCid = ?) temp
7 - 284
                           $where order by date, time");
285
  $sth->execute($RCid, $RCid, $RCid);
13 - 286
  my $hours = 0;
7 - 287
  while (my $s = $sth->fetchrow_hashref) {
288
    my ($yyyy, $mm, $dd) = split /\-/, $s->{date};
289
	  my $cutoff = DateTime->new(
290
        year => $yyyy,
291
        month => $mm,
292
        day => $dd,
293
        hour => 5,
294
        minute => 0,
295
        second => 0,
296
        time_zone => 'America/Los_Angeles'
297
    );
298
 
299
 
300
  	if (!$s->{teams}) {
301
  	  # it's a time-based shift
302
  	  if ($s->{dept} eq "PER") {
303
        if ($RCid eq $ORCUSER->{RCid}) {
304
          # DROP
305
  	      $s->{buttons} = $h->button ({ onClick=>"if (confirm('Really? You want to delete this personal time?')==true) { window.open('manage_personal_time.pl?choice=Delete&id=$s->{id}','Confirm Change','resizable,height=260,width=370'); return false; }" }, "DEL")."&nbsp;".$h->button ({ onClick=>"location.href='manage_personal_time.pl?choice=Update&id=$s->{id}'" }, "EDIT");
306
  	    } else {
307
  	      $s->{location} = "";
308
  	      $s->{role} = "";
309
  	    }
21 - 310
      } elsif (($RCid == $ORCUSER->{RCid} and $s->{signup} !~ /^selected/ and $now < $cutoff) or ($ORCUSER->{department}->{$s->{dept}} >= 2 or $ORCUSER->{access} >= 5)) {
7 - 311
        # DROP
312
  		  $s->{buttons} = $h->button ({ onClick=>"if (confirm('Really? You want to drop this shift?')==true) { window.open('make_shift_change.pl?change=del&id=$s->{id}','Confirm Shift Change','resizable,height=260,width=370'); return false; }" }, "DROP");
313
	   		if ($ORCUSER->{department}->{$s->{dept}} >= 2 or $ORCUSER->{access} >= 5) {
314
   		    # NO SHOW
315
 	  	    $s->{buttons} .= "&nbsp;".$h->button ({ onClick=>"if (confirm('Really? They were a no show?')==true) { window.open('make_shift_change.pl?noshow=true&change=del&RCid=$RCid&id=$s->{id}','Confirm Shift Change','resizable,height=260,width=370'); return false; }" }, "NO SHOW");
316
 		    }
35 - 317
        $hours += $s->{volhours} unless $s->{dept} eq "CLA";
7 - 318
  		}
319
 
21 - 320
    } elsif (($RCid == $ORCUSER->{RCid} and $s->{signup} !~ /^selected/ and $now < $cutoff) or ($ORCUSER->{department}->{$s->{dept}} >= 2 or $ORCUSER->{access} >= 5)) {
7 - 321
      # it's a game shift
322
      #DROP
323
  		$s->{buttons} = $h->button ({ onClick=>"if (confirm('Really? You want to drop this shift?')==true) { window.open('make_shift_change.pl?change=del&RCid=$RCid&id=$s->{id}&role=$s->{role}','Confirm Shift Change','resizable,height=260,width=370'); return false; }" }, "DROP");
324
   		if ($ORCUSER->{department}->{$s->{dept}} >= 2 or $ORCUSER->{access} >= 5) {
325
 		    # NO SHOW
326
        $s->{buttons} .= "&nbsp;".$h->button ({ onClick=>"if (confirm('Really? They were a no show?')==true) { window.open('make_shift_change.pl?noshow=true&change=del&RCid=$RCid&id=$s->{id}&role=$s->{role}','Confirm Shift Change','resizable,height=260,width=370'); return false; }" }, "NO SHOW");
327
      }
328
      $hours += $s->{volhours};
329
  	}
330
  	$s->{role} =~ s/\-\d$//;
331
 
9 - 332
#  	push @shifts, $h->li ({ class=> $s->{date} eq $dt ? "nowrap highlighted" : "nowrap shaded" }, join '&nbsp;&nbsp;', $s->{date}, $s->{dayofweek}, $s->{time}, $s->{location}, getDepartments()->{$s->{dept}}, $s->{role}, $s->{teams}, $s->{buttons});
333
#  	push @shifts, $h->li ({ class=> $s->{date} eq $dt ? "highlighted" : "shaded" }, join '&nbsp;&nbsp;', $s->{date}, $s->{dayofweek}, $s->{time}, $s->{location}, getDepartments()->{$s->{dept}}, $s->{role}, $s->{teams}, $s->{buttons});
334
  	push @shifts, $h->li ({ class=> $s->{date} eq $dt ? "highlighted" : "shaded" }, $h->div ({ class=>"lisp0" }, [ $h->div ({ class=>"liLeft" }, join '&nbsp;&nbsp;', ($s->{date}, $s->{dayofweek}, $s->{time}, $s->{location}, getDepartments()->{$s->{dept}}, $s->{role}, $s->{teams})), $h->div ({ class=>"liRight" }, $s->{buttons}) ]));
7 - 335
  }
336
 
337
  if (scalar @shifts) {
338
    return $h->ul ([ @shifts, $h->h5 ("Currently showing $hours hours of Volunteer Time.") ]);
339
  } else {
340
    return $h->p ({ class=>"hint" }, "[nothing scheduled at the moment]");
341
  }
342
}
343
 
29 - 344
sub getRCid {
345
  my $derbyname = shift;
346
  ($derbyname) = $dbh->selectrow_array ("select RCid from official where derby_name = ?", undef, $derbyname);
347
  return $derbyname;
348
}
349
 
2 - 350
sub getSetting {
351
	my $k = shift;
19 - 352
	my ($value) = $dbh->selectrow_array ("select setting.value from setting where setting.key = ?", undef, $k);
29 - 353
  return defined $value ? $value : undef;
2 - 354
}
355
 
356
sub getUser {
7 - 357
	my $ID = shift;
358
 
359
	my $sth;
360
	if ($ID =~ /^\d+$/) {
361
	  $sth = $dbh->prepare("select * from official where RCid = ?");
362
	} else {
363
	  $sth = $dbh->prepare("select * from official where email = ?");
364
  }
365
	$sth->execute($ID);
366
	return $sth->fetchrow_hashref;
2 - 367
}
368
 
369
sub getUserEmail {
370
	my $RCid = shift;
371
	my $sth = $dbh->prepare("select email from official where RCid = ?");
372
	$sth->execute($RCid);
373
	my ($email) = $sth->fetchrow_array();
374
	return $email;
375
}
376
 
377
sub getUserDerbyName {
378
	my $RCid = shift;
379
	my $sth = $dbh->prepare("select derby_name from official where RCid = ?");
380
	$sth->execute($RCid);
381
	my ($dname) = $sth->fetchrow_array();
382
	return $dname;
383
}
384
 
385
sub getYears {
7 - 386
#	my $sth = $dbh->prepare("select distinct year(date) from v_shift_admin_view union select year(now())");
387
	my $sth = $dbh->prepare("select distinct year(date) from v_shift_admin_view");
2 - 388
	$sth->execute();
389
	my @years;
390
	while (my ($y) =$sth->fetchrow_array()) { push @years, $y; }
391
	return \@years;
392
}
393
 
394
sub printRCHeader {
395
	my $PAGE_TITLE = shift;
7 - 396
	use CGI qw/start_html/;
397
	use HTML::Tiny;
398
  my $h = HTML::Tiny->new( mode => 'html' );
2 - 399
 
7 - 400
#  my $logout = $h->a ({ href=>"index.pl", onClick=>"document.cookie = 'RCAUTH=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/';return true;" }, "[Log Out]");
9 - 401
  my $referrer = param ("referrer") ? param ("referrer") : $ENV{HTTP_REFERER};
402
  my $logout = (!$referrer or $referrer eq url) ? "" : $h->button ({ onClick=>"window.location.href='$referrer';" }, "Back")."&nbsp;";
403
  $logout .= url =~ /\/(index.pl)?$/ ? "" : $h->button ({ onClick=>"window.location.href='/schedule/';" }, "Home")."&nbsp;";
404
  $logout .= $h->button ({ onClick=>"document.cookie = 'RCAUTH=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/'; location.href='/';" }, "Log Out");
405
	my $loggedinas = $ORCUSER ? "Currently logged in as: ".$h->a ({ href=>"/schedule/manage_user.pl?submit=View&RCid=$ORCUSER->{RCid}" }, $ORCUSER->{derby_name}).$h->br.$logout : "";
7 - 406
 
407
  print start_html (-title=>"vORC - $PAGE_TITLE", -style => {'src' => "/style.css"} );
408
 
409
#<html><head><title>Officials' RollerCon Schedule Manager - $PAGE_TITLE</title>
410
#<link rel="stylesheet" type="text/css" href="/style.css">
411
#</head>
412
#<body text="#000000" bgcolor="#FFFFFF" link="#0000EE" vlink="#551A8B" alink="#FF0000">
413
	print $h->div ({ class=>"sp0" }, [ $h->div ({ class=>"spLeft" },  $h->a ({ href=>"/schedule/" }, $h->img ({ src=>"/logo.jpg", width=>"75", height=>"75" }))),
414
	                                   $h->div ({ class=>"spRight" }, [ $h->h1 (["vORC $PAGE_TITLE", $h->br]),
415
	                                   $loggedinas,
416
	                                   ])
417
	                                 ]);
418
#print<<rcheader;
419
#  <TABLE>
420
#	<TR class="nostripe">
421
#		<TD align=right><img SRC="/logo.jpg"></TD>
422
#		<TD align=center valign=middle><b><font size=+3>Officials' RollerCon<br>Schedule Manager<br>$PAGE_TITLE</FONT></b>
423
#	<p align=right><font size=-2>$loggedinas <a href='index.pl' onClick="document.cookie = 'RCAUTH=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/';return true;">[Log Out]</a></font></TD>
424
#	</TR>
2 - 425
 
7 - 426
#rcheader
2 - 427
}
428
 
429
sub changeShift {
7 - 430
	my ($change, $shift_id, $role, $user_id) = @_;
431
	my $leadership_change = 0;
35 - 432
#	my $department = getShiftDepartment ($role ? $shift_id."-".$role : $shift_id);
433
	my $department;
434
	if ($shift_id =~ /^\d+$/) {
435
		$department = getShiftDepartment ($role ? $shift_id."-".$role : $shift_id);
436
	} else {
437
		$department = "CLA";
438
		($shift_id) = $dbh->selectrow_array ("select min(id) from v_shift where date = ? and start_time = ? and location = ? and isnull(RCid) = 1", undef, split /\|/, $shift_id);
439
	}
7 - 440
	my $game_based = $role ? "game" : "shift";
441
	my $sth;
2 - 442
 
46 - 443
	if ($change eq "add" or $change eq "override") {
7 - 444
  	my $taken;
445
  	if ($game_based eq "game") {
446
  	  ($taken) = $dbh->selectrow_array ("select count(*) from assignment where Gid = ? and role = ?", undef, $shift_id, $role);
35 - 447
		} elsif ($department eq "CLA") {
448
  	  ($taken) = $shift_id ? 0 : 1;
7 - 449
  	} else {
450
  	  ($taken) = $dbh->selectrow_array ("select count(*) from shift where id = ? and isnull(assignee_id) = 0", undef, $shift_id);
451
  	}
452
  	if ($taken) {
35 - 453
  	    return ($department eq "CLA") ? "<br>Denied! This class is already full ($shift_id).<br>\n" : "<br>Denied! This shift is already taken ($shift_id).<br>\n";
7 - 454
  	}
455
  }
2 - 456
 
7 - 457
	if (lc ($user_id) ne lc ($ORCUSER->{RCid})) { # they're changing someone else's schedule...
35 - 458
	  if ($ORCUSER->{department}->{$department} >= 2 or $ORCUSER->{access} >= 5 or $ORCUSER->{department}->{VCI} >= 2) {
459
	    # the user making the change is either a lead in the dept, a sysadmin, or a VCI lead
7 - 460
	    logit ($ORCUSER->{RCid}, "$ORCUSER->{derby_name} changed someone else's schedule. ($change, $shift_id, $role, $user_id)");
461
	    logit ($user_id, "Schedule was changed by $ORCUSER->{derby_name}. ($change, $shift_id, $role, $user_id)");
462
	    $leadership_change = 1;
2 - 463
	  } else {
7 - 464
	    logit ($ORCUSER->{RCid}, "Unauthorized attempt to change someone else's schedule. ($change, $shift_id, $role, $user_id)");
465
	    return "<br>Denied! You are not authorized to change someone else's schedule in this department ($department).<br>\n";
2 - 466
	  }
7 - 467
	} elsif ($ORCUSER->{department}->{$department} >= 3) {
468
	  # Managers can sign up for as many shifts within their own department as they like...
469
	  $leadership_change = 1;
2 - 470
	}
471
 
7 - 472
  if ($change eq "add" and convertDepartments(getUser($user_id)->{department})->{$department} < 1) {
29 - 473
		return "<br>Denied! User ($user_id) is not a member of Department ($department)!<br>\n" unless $department eq "CMP";
7 - 474
  }
475
 
46 - 476
  my $conflict = findConflict ($user_id, $shift_id, $game_based);
477
  if ($change eq "add" and $conflict) {
478
		return "<br>Denied! There is a conflict ($conflict) with that shift's time!<br>\n";
7 - 479
  }
480
 
481
 	my ($game_type) = $dbh->selectrow_array ("select type from ".$game_based." where id = ?", undef, $shift_id);
482
 	if ($game_type =~ /^selected/ and !$leadership_change) {
29 - 483
 	  return "<br>Denied! Only leadership can make changes to 'selected staffing' shifts!<br>\n" unless $department eq "CMP";
7 - 484
 	}
485
 
486
 	if ($change eq "add" and $game_type eq "lead" and convertDepartments(getUser($user_id)->{department})->{$department} < 2 and $ORCUSER->{access} < 3) {
487
 	  return "<br>Denied! Shift reserved for leadership staff!<br>\n";
488
 	}
489
 
29 - 490
# 	my $MAXSHIFTS = getSetting ("MAX_SHIFT_SIGNUP_PER_DAY");
491
	my $MAXSHIFTS = getSetting ("MAX_SHIFT_SIGNUP_PER_DAY_".$department);
492
	$MAXSHIFTS = getSetting ("MAX_SHIFT_SIGNUP_PER_DAY") unless defined $MAXSHIFTS;
493
	if ($game_type eq "lead" and $department eq "OFF") { $MAXSHIFTS = 99; }
494
 
35 - 495
  my $daily_count;
496
  if ($department eq "CLA") {
497
    # MVP Class Sign-up
498
    $MAXSHIFTS = getSetting ("MAX_CLASS_SIGNUP");
499
	  ($daily_count) = $dbh->selectrow_array ("select count(*) from v_shift where RCid = ? and dept = 'CLA'", undef, $user_id);
500
   	if ($change eq "add" and $daily_count >= $MAXSHIFTS and !$leadership_change) {
501
	    return "<br>Denied! You may only sign up for $MAXSHIFTS Classes!<br>\n";
502
	  }
503
  } else {
504
   	$daily_count = signUpCount ('get', $user_id, $department);
505
   	if ($change eq "add" and $daily_count >= $MAXSHIFTS and !$leadership_change) {
506
   		return "<br>Denied! You may only sign up for $MAXSHIFTS $game_type shifts in one day!<br>\n";
507
   	}
46 - 508
#   	if ($change eq "add" and $game_based eq "game" and $department eq "OFF" and $game_type eq "full length") {
509
#    	my ($full_length_count) = $dbh->selectrow_array ("select count(*) from v_shift_officiating where RCid = ? and gtype = 'full length' and date > '2022-01-01'", undef, $user_id);
510
#  		if ($full_length_count >= 3) {
511
#  			return "<br>Denied! You may only sign up to officiate 3 $game_type games (total)!<br>\n";
512
#  		}
513
#    }
35 - 514
  }
515
 
7 - 516
 	my @DBARGS;
517
  if ($game_based eq "game") {
46 - 518
  	if ($change eq "add" or $change eq "override") {
7 - 519
  		$sth = $dbh->prepare("insert into assignment (Gid, role, RCid) values (?, ?, ?)");
520
  	} elsif ($change eq "del") {
521
  		$sth = $dbh->prepare("delete from assignment where Gid = ? and role = ? and RCid= ?");
522
  	}
523
  	@DBARGS = ($shift_id, $role, $user_id);
524
  } else {
46 - 525
  	if ($change eq "add" or $change eq "override") {
35 - 526
  		$sth = $dbh->prepare("update shift set assignee_id = ? where id = ? and isnull(assignee_id) = 1");
7 - 527
  		@DBARGS = ($user_id, $shift_id);
528
  	} elsif ($change eq "del") {
529
  		$sth = $dbh->prepare("update shift set assignee_id = null where id = ?");
530
  		@DBARGS = ($shift_id);
531
  	}
532
  }
533
 
534
  print "<br>attempting to make DB changes...<br>";
535
  if ($sth->execute (@DBARGS)) {
29 - 536
  	$daily_count = signUpCount ($change, $user_id, $department) unless $leadership_change;
7 - 537
  	logit ($user_id, "Shift ".ucfirst($change).": $shift_id -> $role");
46 - 538
  	logit ($ORCUSER->{RCid}, "OVERRIDE: Shift ".ucfirst($change).": $shift_id -> $role") if $change eq "override";
7 - 539
  	print "Success!...<br>You've signed up for $daily_count shifts today (you're currently allowed to sign up for $MAXSHIFTS per day).<br>\n";
540
  	return;
541
  } else {
542
    return "<br><b>You did not get the shift</b>, most likely because someone else took it while you were looking.<br>\nERROR: ", $sth->errstr();
543
  }
544
}
545
 
546
sub modShiftTime {
547
	my ($shift_id, $user_id, $diff) = @_;
548
	my $ORCUSER = getUser (1);
2 - 549
 
7 - 550
	use Scalar::Util qw(looks_like_number);
551
	if (!looks_like_number ($diff)) {
552
	  print "<br>ERROR! The time adjustment ($diff) doesn't look like a number.<br>\n";
553
  	return;
2 - 554
	}
555
 
7 - 556
  my ($validate_assignee) = $dbh->selectrow_array ("select count(*) from v_shift where id = ? and RCid = ?", undef, $shift_id, $user_id);
557
 	if (!$validate_assignee) {
558
	  print "<br>ERROR! This shift is assigned to someone else.<br>\n";
559
  	return;
560
 	}
561
 
562
	my $department = getShiftDepartment ($shift_id);
563
  if (convertDepartments ($ORCUSER->{department})->{$department} < 2 and $ORCUSER->{access} < 5) {
564
	  print "<br>ERROR! You're not authorized to modify this shift's time.<br>\n";
565
	  logit ($ORCUSER->{RCid}, "Unauthorized attempt to modify shift time. ($department, $shift_id)");
566
  	return;
567
 	}
568
 
569
  my $rows_changed;
570
  print "<br>attempting to make DB changes...<br>";
571
  if ($diff == 0) {
572
	  $rows_changed = $dbh->do ("update shift set mod_time = null where id = ? and assignee_id = ?", undef, $shift_id, $user_id);
573
  } else {
574
	  $rows_changed = $dbh->do ("update shift set mod_time = ? where id = ? and assignee_id = ?", undef, $diff, $shift_id, $user_id);
575
  }
576
 
577
 
578
  if (!$rows_changed or $dbh->errstr) {
579
  	print "ERROR: Nothing got updated".$dbh->errstr;
580
  	logit (0, "ERROR modifying a shift time ($diff, $shift_id, $user_id):".$dbh->errstr);
581
  } else {
582
  	print "SUCCESS: Shift $shift_id succesfully modified by $diff hour(s)";
583
  	logit ($ORCUSER->{RCid}, "SUCCESS: Shift $shift_id succesfully modified by $diff hour(s)");
584
 
585
  }
586
  return;
2 - 587
}
588
 
589
sub signUpCount {
590
	my $action = shift;
591
	my $id = shift;
19 - 592
	my $dept = shift // "";
2 - 593
 
7 - 594
	if ($id eq $ORCUSER->{RCid}) {
2 - 595
		if ($action eq 'add') {
19 - 596
			if (signUpCount ('get', $id, $dept)) {
597
				$dbh->do("update sign_up_count set sign_ups = sign_ups + 1 where date = curdate() and RCid = ? and department = ?", undef, $id, $dept);
2 - 598
			} else {
19 - 599
				$dbh->do("replace into sign_up_count (date, RCid, department, sign_ups) values (curdate(), ?, ?, 1)", undef, $id, $dept);
2 - 600
			}
601
		} elsif ($action eq 'del') {
19 - 602
			if (signUpCount ('get', $id, $dept)) {
603
				$dbh->do("update sign_up_count set sign_ups = sign_ups - 1 where date = curdate() and RCid = ? and department = ?", undef, $id, $dept);
2 - 604
			}
605
		}
606
	}
607
 
19 - 608
	my ($R) = $dbh->selectrow_array ("select sign_ups from sign_up_count where RCid = ? and department = ? and date = curdate()", undef, $id, $dept);
2 - 609
 
610
	return $R ? $R : '0';
611
}
612
 
613
sub signUpEligible {
614
	my $user = shift;
615
	my $t = shift;
7 - 616
	my $shifttype = shift // "game";
19 - 617
	my $dept = $t->{dept} // "";
2 - 618
 
19 - 619
	my $limit = getSetting ("MAX_SHIFT_SIGNUP_PER_DAY_".$dept);
620
	$limit = getSetting ("MAX_SHIFT_SIGNUP_PER_DAY") unless defined $limit;
621
 
29 - 622
	if ($t->{type} eq "lead" and $dept eq "OFF") { $limit = 99; }
623
 
624
	return 0 unless $limit > 0;
625
 
19 - 626
	my $limitkey = $dept ? "sign_ups_today_".$dept : "sign_ups_today";
627
 
35 - 628
	if ($shifttype eq "class") {
629
		($t->{id}) = $dbh->selectrow_array ("select min(id) from v_shift where isnull(RCid) = 1 and dept = ? and date = ? and location = ? and start_time = ?", undef, "CLA", $t->{date}, $t->{location}, $t->{start_time});
630
		$t->{dept} = "CLA";
631
		$t->{type} = "open";
632
	}
633
 
7 - 634
	if (findConflict ($user->{RCid}, $t->{id}, $shifttype)) { return 0; }
635
 
19 - 636
	if (!exists $user->{$limitkey}) {
637
		$user->{$limitkey} = signUpCount('get', $user->{RCid}, $dept);
2 - 638
	}
639
 
7 - 640
	if ($shifttype eq "game") {
21 - 641
#    if ($t->{gtype} !~ /^selected/ and $t->{gtype} ne "short track" and $user->{$limitkey} < $limit) {
46 - 642
#		if ($t->{gtype} eq "full length" and $dept eq "OFF") {
643
#			my ($full_length_count) = $dbh->selectrow_array ("select count(*) from v_shift_officiating where RCid = ? and gtype = 'full length' and date > '2022-01-01'", undef, $user->{RCid});
644
#			if ($full_length_count >= 3) {
645
#				return 0;
646
#			}
647
#		}
21 - 648
    if ($t->{signup} ne "selected" and $user->{$limitkey} < $limit) {
2 - 649
			return 1;
650
		} else {
651
			return 0;
652
		}
7 - 653
	} else {
35 - 654
    if ($dept eq "CLA") {
655
      # MVP Class Sign-up
656
      my $class_limit = getSetting ("MAX_CLASS_SIGNUP");
657
			my ($class_count) = $dbh->selectrow_array ("select count(*) from v_shift where RCid = ? and dept = 'CLA'", undef, $user->{RCid});
658
			return 0 unless $class_count < $class_limit;
659
    }
7 - 660
	  if ($user->{department}->{$t->{dept}} < 1) { return 0; }
661
	  if ($t->{type} eq "lead" and $user->{department}->{$t->{dept}} < 2) { return 0; }
662
	  if ($t->{type} eq "manager" and $user->{department}->{$t->{dept}} < 3) { return 0; }
19 - 663
    if ($t->{type} !~ /^selected/ and $user->{$limitkey} < $limit) {
2 - 664
			return 1;
665
		} else {
666
			return 0;
667
		}
668
	}
669
}
670
 
671
sub findConflict {
672
  my $rcid = shift;
673
  my $gid = shift;
7 - 674
  my $type = shift // "";
675
  my ($date, $start, $end, $conflicts);
2 - 676
 
7 - 677
  if ($type eq "game") {
678
  # Are they already signed up for this game? (It's faster to check the two views one at a time...)
679
#    ($conflicts) = $dbh->selectrow_array ("select count(*) from v_shift_officiating where substring_index(id, '-', 1) = ? and RCid = ?", undef, $gid, $rcid);
680
    ($conflicts) = $dbh->selectrow_array ("select count(*) from v_shift_officiating where id = ? and RCid = ?", undef, $gid, $rcid);
46 - 681
  	if ($conflicts) { return "OFF-".$gid; } # no need to keep looking...
7 - 682
    ($conflicts) = $dbh->selectrow_array ("select count(*) from v_shift_announcer where id = ? and RCid = ?", undef, $gid, $rcid);
46 - 683
  	if ($conflicts) { return "ANN-".$gid; } # no need to keep looking...
7 - 684
 
685
    ($date, $start, $end) = $dbh->selectrow_array ("select distinct date, time, end_time from game where id = ?", undef, $gid);
686
  } elsif ($type eq "personal")  {
687
    ($date, $start, $end) = @{ $gid };
688
  } else {
689
    ($date, $start, $end) = $dbh->selectrow_array ("select distinct date, start_time, end_time from shift where id = ?", undef, $gid);
690
  }
2 - 691
 
692
  # Are they signed up for any games that would conflict with this one?
7 - 693
#  my $sth = $dbh->prepare("select count(*) from v_shift_admin_view where id in (select id from game where date = (select date from game where id = ?) and ((time <= (select time from game where id = ?) and end_time > (select time from game where id = ?)) or (time > (select time from game where id = ?) and time < (select end_time from game where id = ?)))) and RCid = ?");
694
#  my $sth = $dbh->prepare("select count(*) from v_shift_all where id in (select id from v_shift_all where date = (select date from v_shift_all where id = ?) and ((start_time <= (select start_time from v_shift_all where id = ?) and end_time > (select start_time from v_shift_all where id = ?)) or (start_time > (select start_time from v_shift_all where id = ?) and start_time < (select end_time from v_shift_all where id = ?)))) and RCid = ?");
2 - 695
 
46 - 696
  ($conflicts) = $dbh->selectrow_array ("select * from (
697
    select concat(dept, '-', id) from v_shift             where date = ? and ((start_time <= ? and end_time > ?) or (start_time > ? and start_time < ?)) and RCid = ? union
698
    select concat('ANN-', id) from v_shift_announcer   where date = ? and ((start_time <= ? and end_time > ?) or (start_time > ? and start_time < ?)) and RCid = ? union
699
    select concat('OFF-', id) from v_shift_officiating where date = ? and ((start_time <= ? and end_time > ?) or (start_time > ? and start_time < ?)) and RCid = ? ) alltables",
7 - 700
    undef, $date, $start, $start, $start, $end, $rcid, $date, $start, $start, $start, $end, $rcid, $date, $start, $start, $start, $end, $rcid
701
  );
702
 
2 - 703
  return $conflicts;
704
}
705
 
706
sub changeLeadShift {
707
	my ($change, $lshift, $user_id) = @_;
708
	my $ERRMSG;
709
 
710
	my $sth = $dbh->prepare("update lead_shift set assignee_id = ? where id = ?");
711
 
712
	print "<br>attempting to make DB changes...<br>";
713
	if ($change eq "add") {
714
		$sth->execute($user_id, $lshift)
715
    	or $ERRMSG = "ERROR: Can't execute SQL statement: ".$sth->errstr()."\n";
716
	} elsif ($change eq "del") {
717
		$sth->execute('', $lshift)
718
    	or $ERRMSG = "ERROR: Can't execute SQL statement: ".$sth->errstr()."\n";
719
	}
720
	if ($ERRMSG) {
721
		print $ERRMSG;
722
	} else {
723
		logit($user_id, "Lead Shift ".ucfirst($change).": $lshift");
724
  	print "Success.<br>";
725
  }
726
}
727
 
728
sub logit {
729
	my $RCid = shift;
730
	my $msg = shift;
731
	my $sth = $dbh->prepare("insert into log (RCid, event) values (?, ?)");
732
	$sth->execute($RCid, $msg);
733
}
734
 
735
1;