Subversion Repositories VORC

Rev

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

Rev Author Line No. Line
105 bgadell 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 cPanelUserConfig;
11
use WebDB;
12
use HTML::Tiny;
13
use RollerCon;
226 - 14
use CGI qw/param header start_html url url_param/;
105 bgadell 15
my $h = HTML::Tiny->new( mode => 'html' );
16
 
17
my %F;
18
 
19
my $cookie_string = authenticate (RollerCon::SYSADMIN) || die;
20
my $RCAUTH_cookie = CGI::Cookie->new(-name=>'RCAUTH',-value=>"$cookie_string",-expires=>"+30m");
21
our ($EML, $PWD, $LVL) = split /&/, $cookie_string;
22
my $user = getUser ($EML);
23
$user->{department} = convertDepartments $user->{department};
24
my $DepartmentNames = getDepartments ();
25
my $username = $user->{derby_name};
26
my $RCid = $user->{RCid};
27
my $RCAUTH_cookie = CGI::Cookie->new(-name=>'RCAUTH',-value=>"$cookie_string",-expires=>"+30m");
28
my $YEAR = 1900 + (localtime)[5];
29
 
30
 
31
my $pageTitle = "View Class Survey Question";
32
my $homeURL = "/schedule/";
33
my $DBTable = "survey_question";
34
my %FIELDS = (
35
	qid          => [qw(QID           5    auto        static )],
36
	qorder       => [qw(Order        10    number      required )],
37
	question     => [qw(Question     20    text        required )],
38
	type         => [qw(Type         30    select      required )],
39
	required     => [qw(Required     40    switch      required )],
40
	private      => [qw(Private      45    switch      required )],
41
	added        => [qw(Timestamp    50    auto     )],
42
);
43
 
44
 
45
my %fieldDisplayName = map  { $_ => $FIELDS{$_}->[0]   } keys %FIELDS;
46
my %fieldType        = map  { $_ => $FIELDS{$_}->[2]   } keys %FIELDS;
47
my @requiredFields   = sort fieldOrder grep { defined $FIELDS{$_}->[3] } keys %FIELDS;
48
my @DBFields   = sort fieldOrder grep { $fieldType{$_} =~ /^(text|select|number|switch|date|time|auto)/ } keys %FIELDS;
49
my @ROFields   = sort fieldOrder grep { $fieldType{$_} =~ /^(readonly)/ } keys %FIELDS;
50
my $primary = $DBFields[0];
51
 
52
sub fieldOrder {
53
	$FIELDS{$a}->[1] <=> $FIELDS{$b}->[1];
54
}
55
 
56
sub saveForm {
57
  error ("ERROR: Only SysAdmins can change games.") unless $LVL >= RollerCon::ADMIN;
58
 
59
  my $FTS = shift;
60
 
61
  my $dbh = WebDB::connect ();
62
  if ($FTS->{$DBFields[0]} eq "NEW") {
63
    $dbh->do (
64
      "INSERT INTO $DBTable
65
      (qorder,question,type,required,private,added)
66
      VALUES(?,?,?,?,?,now())",
67
    	undef,
68
    	$FTS->{qorder}, $FTS->{question}, $FTS->{type}, $FTS->{required}, $FTS->{private}
69
    ) or warn $dbh->errstr;
70
  	($FTS->{qid}) = $dbh-> selectrow_array ("select max(qid) from $DBTable where qorder = ? and question = ? and type = ? and required = ? and private = ?", undef, $FTS->{qorder}, $FTS->{question}, $FTS->{type}, $FTS->{required}), $FTS->{private};
71
    logit ($RCid, "$username created new survey question ($FTS->{qid})");
72
 
73
  } else {
74
    $dbh->do (
75
      "UPDATE $DBTable
76
      SET qorder=?, question=?, type=?, required=?, private=?, added=now()
77
      WHERE qid = ?",
78
      undef,
79
      $FTS->{qorder}, $FTS->{question}, $FTS->{type}, $FTS->{required}, $FTS->{private}, $FTS->{qid}
80
    );
81
    logit ($RCid, "$username updated class ($FTS->{qid})");
82
 
83
	}
84
 
85
	$dbh->disconnect ();	 # stored into database successfully.
86
	return $FTS->{qid};
87
}
88
 
89
sub delete_item {
90
  error ("ERROR: Only SysAdmins can change games.") unless $LVL >= RollerCon::ADMIN;
91
 
92
  my $X = shift;
93
  my $dbh = WebDB::connect ();
94
 
95
  $dbh->do ("delete from $DBTable where $primary = ?", undef, $X->{$primary});
96
 
97
  $dbh->disconnect ();
98
  logit ($RCid, "$username deleted Question ($X->{$primary})");
99
  print "Question Deleted: $X->{$primary}", $h->br;
100
  print &formField ("Cancel", "Back", "POSTSAVE");
101
}
102
 
103
 
104
sub select_type {
105
	my $selection = shift // "";
106
 
107
  my @options = qw(range text);
108
 
109
  return $h->select ({ name=>"type" }, [ $h->option (""), map { $selection eq $_ ? $h->option ({selected=>[]}, $_) : $h->option ($_) } @options ]);
110
};
111
 
112
 
113
print header (-cookie=> [ $RCAUTH_cookie ]),
114
			start_html (-title => $pageTitle, -style => {'src' => "/style.css"} );
115
 
116
print $h->div ({ class => "accent pageheader" }, [
117
  $h->h1 ($pageTitle),
118
  $h->div ({ class=>"sp0" }, [
119
    $h->div ({ class=>"spLeft" }, [
120
    ]),
121
    $h->div ({ class=>"spRight" }, [
122
      $h->input ({ type=>"button", value=>"Home", onClick=>"window.location.href='$homeURL'" }),
123
    ]),
124
  ]),
125
]);
126
 
127
my $choice = param ("choice") // "";
128
if ($choice eq "Save") {
129
	process_form ();
226 - 130
} elsif (defined (param ($primary) || url_param ($primary))) {
131
  my $thing = param ($primary); $thing //= url_param ($primary);
105 bgadell 132
  if ($choice eq "Delete") {
133
    delete_item ({ $primary => $thing });
134
  } else {
135
	  display_form ({ $primary => $thing }, $choice);
136
	}
137
} else {
138
	display_form (); # blank form
139
}
140
 
141
print $h->close ("html");
142
 
143
sub display_form  {
144
  my $R = shift;
145
  my $view = shift // "";
146
	my $actionbutton;
147
 
148
  $view = "View" unless $LVL >= RollerCon::ADMIN;
149
 
150
  if ($view eq "POSTSAVE" and $R->{$primary} eq "NEW") {
151
      print &formField ("Cancel", "Back", "POSTSAVE");
152
      return;
153
  }
154
 
155
  if ($R) {
156
    # we're dealing with an existing thing.  Get the current values out of the DB...
157
    my $dbh = WebDB::connect ();
158
 
159
	  @F{@DBFields} = $dbh->selectrow_array (
160
                     "SELECT ". join (", ", @DBFields) ." FROM $DBTable WHERE $primary = ?",
161
                      undef, $R->{$primary});
162
 
163
	  $dbh->disconnect ();
164
 
165
	  # did we find a record?
166
	  error ("Cannot find a database entry for Question with qid: '$R->{$primary}'") unless defined $F{$DBFields[0]};
167
 
168
    # If the DB returns a null value, HTML::Tiny doesn't like it, so make sure nulls are converted to empty strings.
169
    map { $F{$_} = "" unless $F{$_} } @DBFields;
170
 
171
    if ($view eq "Update") {
172
      # We'd like to update that thing, give the user a form...
173
      print $h->p ("Updating Class: $R->{$primary}...");
174
 
175
      foreach (@DBFields) {
176
        $F{$_} = formField ($_, $F{$_});
177
      }
178
      $F{$DBFields[0]} .= $h->input ({ type=>"hidden", name=>$DBFields[0],   value=> $F{$DBFields[0]} });
179
 
180
      $actionbutton = formField ("choice", "Save");
181
      $actionbutton .= formField ("Cancel");
182
    } elsif ($view eq "Copy") {
183
      # We'd like to copy that thing, give the user a form...
184
      print $h->p ("Copying Question: $R->{$primary}...");
185
 
186
      foreach (@DBFields) {
187
        $F{$_} = formField ($_, $F{$_});
188
      }
189
      $F{$DBFields[0]} = "COPY".$h->input ({ type=>"hidden", name=>$DBFields[0], value=> "NEW" });
190
 
191
      $actionbutton = formField ("choice", "Save");
192
      $actionbutton .= formField ("Cancel");
193
    } else {
194
      # We're just looking at it...
195
      print $h->p ("Viewing Question: $R->{$primary}...");
196
      $F{$DBFields[0]} .= $h->input ({ type=>"hidden", name=>$DBFields[0], value=> $F{$DBFields[0]} });
197
 
198
      $F{required} = $F{required} ? "True" : "False";
199
      $F{private}  = $F{private}  ? "True" : "False";
200
 
201
      $actionbutton = formField ("choice", "Update") unless $LVL < RollerCon::ADMIN;
202
      if ($view eq "POSTSAVE" or $choice eq "View") {
203
        $actionbutton .= formField ("Cancel", "Back", "POSTSAVE");
204
      } else {
205
        $actionbutton .= formField ("Cancel", "Back");
206
      }
207
    }
208
  } else {
209
    error ("No Question ID provided.") unless $LVL >= RollerCon::ADMIN;
210
 
211
    print $h->p ("Adding a new Question...");
212
 
213
    foreach (@DBFields) {
214
      $F{$_} = formField ($_);
215
    }
216
		$F{$DBFields[0]} = "NEW".$h->input ({ type=>"hidden", name=>$DBFields[0], value=> "NEW" });
217
 
218
    $actionbutton = formField ("choice", "Save");
219
    $actionbutton .= formField ("Cancel");
220
  }
221
 
222
 
223
	print $h->open ("form", { action => url (), name=>"Req", method=>"POST" });
224
	print $h->div ({ class=>"sp0" },
225
	  $h->div ({ class=>"rTable" }, [ map ({
226
      $h->div ({ class=>"rTableRow" }, [
227
        $h->div ({ class=>"rTableCell right top", style=>"font-size:unset;" }, "$fieldDisplayName{$_}: "),
228
        $h->div ({ class=>"rTableCell", style=>"font-size:unset;" }, $F{$_})
229
      ])
230
       } sort fieldOrder keys %FIELDS),
231
   ])
232
  );
233
 
234
  print $actionbutton;
235
  print $h->close ("form");
236
 
237
}
238
 
239
sub process_form  {
240
  error ("ERROR: Only SysAdmins can change games.") unless $LVL >= RollerCon::ADMIN;
241
 
242
  my %FORM;
243
  foreach (keys %FIELDS) {
244
  	if ($fieldType{$_} =~ /^text/) {
245
  		$FORM{$_} = WebDB::trim param ($_) // "";
246
  	} else {
247
	  	$FORM{$_} = param ($_) // "";
248
  	}
249
#  	warn "FORM: $_: $FORM{$_}";
250
  }
251
  $FORM{required} = 0 unless $FORM{required};
252
  $FORM{private}  = 0 unless $FORM{private};
253
 
254
  	 # check for required fields
255
	my @errors = ();
256
	foreach (@requiredFields) {
257
		push @errors, "$fieldDisplayName{$_} is missing." if $FORM{$_} eq "";
258
	}
259
	push @errors, "Order should be a whole number." unless $FORM{qorder} =~ /^\d+$/;
260
 
261
  if (@errors)	 {
262
    print $h->div ({ class=>"error" }, [
263
  	  $h->p ("The following errors occurred:"),
264
  	  $h->ul ($h->li (@errors)),
265
  	  $h->p ("Please click your Browser's Back button to\n"
266
  	  	   . "return to the previous page and correct the problem.")
267
  	]);
268
  	return;
269
  }	 # Form was okay.
270
 
271
  $FORM{qid} = saveForm (\%FORM);
272
 
273
	if ($FORM{qid}) {
274
	  print $h->p ({ class=>"success" }, "Question successfully saved.");
275
	} else {
276
	  print $h->p ({ class=>"error" }, "Question failed to save.");
277
	}
278
 
279
  display_form ({ $primary=>$FORM{qid} }, "POSTSAVE");
280
}
281
 
282
sub error {
283
	my $msg = shift;
284
	print $h->p ({ class=>"error" }, "Error: $msg");
285
  print $h->close("html");
286
	exit (0);
287
}
288
 
289
sub formField {
290
	my $name  = shift;
291
	my $value = shift // '';
292
	my $context = shift // '';
293
	my $type = $fieldType{$name} // "button";
294
 
295
  if ($type eq "button") {
296
		if ($name eq "Cancel") {
297
		  if ($context eq "POSTSAVE") {
298
		    return $h->input ({ type=>"button", value => $value ne '' ? $value : "Cancel" , onClick=>"window.location.href = \"class_survey_questions.pl\"; return false;" });
299
		  } else {
300
		    return $h->input ({ type=>"button", value => $value ne '' ? $value : "Cancel" , onClick=>"history.back(); return false;" });
301
		  }
302
		} else {
303
			return $h->input ({ type=>"submit", value => $value, name=>$name })
304
		}
305
 
306
	} elsif ($type eq "textarea") {
307
	  return $h->tag ("textarea", {
308
	    name => $name,
309
	    override => 1,
310
			cols => 30,
311
			rows => 4
312
	  }, $value);
313
 
314
  } elsif ($type eq "select") {
315
    no strict;
316
    return &{"select_".$name} ($value);
317
	}	elsif ($type eq "auto") {
318
	  return $name eq "assignee_id" ? getUserDerbyName ($value) : $value;
319
  }	elsif ($type eq "time") {
320
	  return $h->input ({
321
	    name => $name,
322
	    type => $type,
323
	    value => $value,
324
	    step => 900,
325
	    required => [],
326
	    override => 1,
327
	    size => 30
328
	  });
329
  }	elsif ($type eq "number") {
330
    return $h->input ({ name=>$name, type=>"number", value=>$value, step=>1 });
331
  }	elsif ($type eq "switch") {
332
    if ($value) {
333
      return $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>$name, value=>1, checked=>[] }), $h->span ({ class=>"slider round" })]);
334
    } else {
335
      return $h->label ({ class=>"switch" }, [$h->input ({ type=>"checkbox", name=>$name, value=>1 }), $h->span ({ class=>"slider round" })]);
336
    }
337
	}	else {
338
	  use tableViewer;
339
	  if (inArray ($name, \@requiredFields)) {
340
  	  return $h->input ({
341
  	    name => $name,
342
  	    type => $type,
343
  	    value => $value,
344
  	    required => [],
345
  	    override => 1,
346
  	    size => 30
347
  	  });
348
	  } else {
349
  	  return $h->input ({
350
  	    name => $name,
351
  	    type => $type,
352
  	    value => $value,
353
  	    override => 1,
354
  	    size => 30
355
  	  });
356
  	}
357
	}
358
}
359