Subversion Repositories ORC

Rev

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