Parent Directory
|
Revision Log
Added ability to color code the answers
1 ################################################################################ 2 # WeBWorK Online Homework Delivery System 3 # Copyright © 2000-2007 The WeBWorK Project, http://openwebwork.sf.net/ 4 # $CVSHeader: webwork2/lib/WeBWorK/ContentGenerator/Problem.pm,v 1.225 2010/05/28 21:29:48 gage Exp $ 5 # 6 # This program is free software; you can redistribute it and/or modify it under 7 # the terms of either: (a) the GNU General Public License as published by the 8 # Free Software Foundation; either version 2, or (at your option) any later 9 # version, or (b) the "Artistic License" which comes with this package. 10 # 11 # This program is distributed in the hope that it will be useful, but WITHOUT 12 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 13 # FOR A PARTICULAR PURPOSE. See either the GNU General Public License or the 14 # Artistic License for more details. 15 ################################################################################ 16 17 package WeBWorK::ContentGenerator::Problem; 18 use base qw(WeBWorK::ContentGenerator); 19 20 =head1 NAME 21 22 WeBWorK::ContentGenerator::Problem - Allow a student to interact with a problem. 23 24 =cut 25 26 use strict; 27 use warnings; 28 #use CGI qw(-nosticky ); 29 use WeBWorK::CGI; 30 use File::Path qw(rmtree); 31 use WeBWorK::Debug; 32 use WeBWorK::Form; 33 use WeBWorK::PG; 34 use WeBWorK::PG::ImageGenerator; 35 use WeBWorK::PG::IO; 36 use WeBWorK::Utils qw(readFile writeLog writeCourseLog encodeAnswers decodeAnswers 37 ref2string makeTempDirectory path_is_subdir sortByName before after between); 38 use WeBWorK::DB::Utils qw(global2user user2global); 39 use URI::Escape; 40 41 use WeBWorK::Utils::Tasks qw(fake_set fake_problem); 42 43 ################################################################################ 44 # CGI param interface to this module (up-to-date as of v1.153) 45 ################################################################################ 46 47 # Standard params: 48 # 49 # user - user ID of real user 50 # key - session key 51 # effectiveUser - user ID of effective user 52 # 53 # Integration with PGProblemEditor: 54 # 55 # editMode - if set, indicates alternate problem source location. 56 # can be "temporaryFile" or "savedFile". 57 # 58 # sourceFilePath - path to file to be edited 59 # problemSeed - force problem seed to value 60 # success - success message to display 61 # failure - failure message to display 62 # 63 # Rendering options: 64 # 65 # displayMode - name of display mode to use 66 # 67 # showOldAnswers - request that last entered answer be shown (if allowed) 68 # showCorrectAnswers - request that correct answers be shown (if allowed) 69 # showHints - request that hints be shown (if allowed) 70 # showSolutions - request that solutions be shown (if allowed) 71 # 72 # Problem interaction: 73 # 74 # AnSwEr# - answer blanks in problem 75 # 76 # redisplay - name of the "Redisplay Problem" button 77 # submitAnswers - name of "Submit Answers" button 78 # checkAnswers - name of the "Check Answers" button 79 # previewAnswers - name of the "Preview Answers" button 80 81 ################################################################################ 82 # "can" methods 83 ################################################################################ 84 85 # Subroutines to determine if a user "can" perform an action. Each subroutine is 86 # called with the following arguments: 87 # 88 # ($self, $User, $EffectiveUser, $Set, $Problem) 89 90 # Note that significant parts of the "can" methods are lifted into the 91 # GatewayQuiz module. It isn't direct, however, because of the necessity 92 # of dealing with versioning there. 93 94 sub can_showOldAnswers { 95 #my ($self, $User, $EffectiveUser, $Set, $Problem) = @_; 96 97 return 1; 98 } 99 100 sub can_showCorrectAnswers { 101 my ($self, $User, $EffectiveUser, $Set, $Problem) = @_; 102 my $authz = $self->r->authz; 103 104 return 105 after($Set->answer_date) 106 || 107 $authz->hasPermissions($User->user_id, "show_correct_answers_before_answer_date") 108 ; 109 } 110 111 sub can_showHints { 112 #my ($self, $User, $EffectiveUser, $Set, $Problem) = @_; 113 114 return 1; 115 } 116 117 sub can_showSolutions { 118 my ($self, $User, $EffectiveUser, $Set, $Problem) = @_; 119 my $authz = $self->r->authz; 120 121 return 122 after($Set->answer_date) 123 || 124 $authz->hasPermissions($User->user_id, "show_solutions_before_answer_date") 125 ; 126 } 127 128 sub can_recordAnswers { 129 my ($self, $User, $EffectiveUser, $Set, $Problem, $submitAnswers) = @_; 130 my $authz = $self->r->authz; 131 my $thisAttempt = $submitAnswers ? 1 : 0; 132 if ($User->user_id ne $EffectiveUser->user_id) { 133 return $authz->hasPermissions($User->user_id, "record_answers_when_acting_as_student"); 134 } 135 if (before($Set->open_date)) { 136 return $authz->hasPermissions($User->user_id, "record_answers_before_open_date"); 137 } elsif (between($Set->open_date, $Set->due_date)) { 138 my $max_attempts = $Problem->max_attempts; 139 my $attempts_used = $Problem->num_correct + $Problem->num_incorrect + $thisAttempt; 140 if ($max_attempts == -1 or $attempts_used < $max_attempts) { 141 return $authz->hasPermissions($User->user_id, "record_answers_after_open_date_with_attempts"); 142 } else { 143 return $authz->hasPermissions($User->user_id, "record_answers_after_open_date_without_attempts"); 144 } 145 } elsif (between($Set->due_date, $Set->answer_date)) { 146 return $authz->hasPermissions($User->user_id, "record_answers_after_due_date"); 147 } elsif (after($Set->answer_date)) { 148 return $authz->hasPermissions($User->user_id, "record_answers_after_answer_date"); 149 } 150 } 151 152 sub can_checkAnswers { 153 my ($self, $User, $EffectiveUser, $Set, $Problem, $submitAnswers) = @_; 154 my $authz = $self->r->authz; 155 my $thisAttempt = $submitAnswers ? 1 : 0; 156 157 if (before($Set->open_date)) { 158 return $authz->hasPermissions($User->user_id, "check_answers_before_open_date"); 159 } elsif (between($Set->open_date, $Set->due_date)) { 160 my $max_attempts = $Problem->max_attempts; 161 my $attempts_used = $Problem->num_correct + $Problem->num_incorrect + $thisAttempt; 162 if ($max_attempts == -1 or $attempts_used < $max_attempts) { 163 return $authz->hasPermissions($User->user_id, "check_answers_after_open_date_with_attempts"); 164 } else { 165 return $authz->hasPermissions($User->user_id, "check_answers_after_open_date_without_attempts"); 166 } 167 } elsif (between($Set->due_date, $Set->answer_date)) { 168 return $authz->hasPermissions($User->user_id, "check_answers_after_due_date"); 169 } elsif (after($Set->answer_date)) { 170 return $authz->hasPermissions($User->user_id, "check_answers_after_answer_date"); 171 } 172 } 173 174 # Reset the default in some cases 175 sub set_showOldAnswers_default { 176 my ($self, $ce, $userName, $authz, $set) = @_; 177 # these people always use the system/course default, so don't 178 # override the value of ...->{showOldAnswers} 179 return if $authz->hasPermissions($userName, "can_always_use_show_old_answers_default"); 180 # this person should always default to 0 181 $ce->{pg}->{options}->{showOldAnswers} = 0 182 unless ($authz->hasPermissions($userName, "can_show_old_answers_by_default")); 183 # we are after the due date, so default to not showing it 184 $ce->{pg}->{options}->{showOldAnswers} = 0 if $set->{due_date} && after($set->{due_date}); 185 } 186 187 ################################################################################ 188 # output utilities 189 ################################################################################ 190 191 # Note: the substance of attemptResults is lifted into GatewayQuiz.pm, 192 # with some changes to the output format 193 194 sub attemptResults { 195 my $self = shift; 196 my $pg = shift; 197 my $showAttemptAnswers = shift; 198 my $showCorrectAnswers = shift; 199 my $showAttemptResults = $showAttemptAnswers && shift; 200 my $showSummary = shift; 201 my $showAttemptPreview = shift || 0; 202 203 my $ce = $self->r->ce; 204 205 # for color coding the responses. 206 my @correct_ids = (); 207 my @incorrect_ids = (); 208 209 210 my $problemResult = $pg->{result}; # the overall result of the problem 211 my @answerNames = @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} }; 212 213 my $showMessages = $showAttemptAnswers && grep { $pg->{answers}->{$_}->{ans_message} } @answerNames; 214 215 my $basename = "equation-" . $self->{set}->psvn. "." . $self->{problem}->problem_id . "-preview"; 216 217 # to make grabbing these options easier, we'll pull them out now... 218 my %imagesModeOptions = %{$ce->{pg}->{displayModeOptions}->{images}}; 219 220 my $imgGen = WeBWorK::PG::ImageGenerator->new( 221 tempDir => $ce->{webworkDirs}->{tmp}, 222 latex => $ce->{externalPrograms}->{latex}, 223 dvipng => $ce->{externalPrograms}->{dvipng}, 224 useCache => 1, 225 cacheDir => $ce->{webworkDirs}->{equationCache}, 226 cacheURL => $ce->{webworkURLs}->{equationCache}, 227 cacheDB => $ce->{webworkFiles}->{equationCacheDB}, 228 dvipng_align => $imagesModeOptions{dvipng_align}, 229 dvipng_depth_db => $imagesModeOptions{dvipng_depth_db}, 230 ); 231 232 my $header; 233 #$header .= CGI::th("Part"); 234 #$header .= $showAttemptAnswers ? CGI::th("Entered") : ""; 235 $header .= $showAttemptPreview ? CGI::th("Answer Preview") : ""; 236 $header .= $showCorrectAnswers ? CGI::th("Correct") : ""; 237 $header .= $showAttemptResults ? CGI::th("Result") : ""; 238 $header .= $showMessages ? CGI::th("Messages") : ""; 239 my $fully = ''; 240 my @tableRows = ( $header ); 241 my $numCorrect = 0; 242 my $numBlanks =0; 243 my $tthPreambleCache; 244 foreach my $name (@answerNames) { 245 my $answerResult = $pg->{answers}->{$name}; 246 my $studentAnswer = $answerResult->{student_ans}; # original_student_ans 247 my $preview = ($showAttemptPreview 248 ? $self->previewAnswer($answerResult, $imgGen, \$tthPreambleCache) 249 : ""); 250 my $correctAnswerPreview = $self->previewCorrectAnswer($answerResult, $imgGen, \$tthPreambleCache); 251 my $correctAnswer = $answerResult->{correct_ans}; 252 my $answerScore = $answerResult->{score}; 253 my $answerMessage = $showMessages ? $answerResult->{ans_message} : ""; 254 $answerMessage =~ s/\n/<BR>/g; 255 $numCorrect += $answerScore >= 1; 256 $numBlanks++ unless $studentAnswer =~/\S/ || $answerScore >= 1; # unless student answer contains entry 257 my $resultString = $answerScore >= 1 ? CGI::span({class=>"ResultsWithoutError"}, "correct") : 258 $answerScore > 0 ? int($answerScore*100)."% correct" : 259 CGI::span({class=>"ResultsWithError"}, "incorrect"); 260 $fully = 'completely ' if $answerScore >0 and $answerScore < 1; 261 262 push @correct_ids, $name if $answerScore == 1; 263 push @incorrect_ids, $name if $answerScore < 1; 264 265 # get rid of the goofy prefix on the answer names (supposedly, the format 266 # of the answer names is changeable. this only fixes it for "AnSwEr" 267 #$name =~ s/^AnSwEr//; 268 269 my $row; 270 #$row .= CGI::td($name); 271 #$row .= $showAttemptAnswers ? CGI::td($self->nbsp($studentAnswer)) : ""; 272 $row .= $showAttemptPreview ? CGI::td({onmouseover=>qq!Tip('$studentAnswer',SHADOW, true, 273 DELAY, 1000, FADEIN, 300, FADEOUT, 300, STICKY, 1, OFFSETX, -20, CLOSEBTN, true, CLICKCLOSE, false, 274 BGCOLOR, '#F4FF91', TITLE, 'Entered:',TITLEBGCOLOR, '#F4FF91', TITLEFONTCOLOR, '#000000')!}, 275 $self->nbsp($preview)) : ""; 276 $row .= $showCorrectAnswers ? CGI::td({onmouseover=> qq!Tip('$correctAnswer',SHADOW, true, 277 DELAY, 1000, FADEIN, 300, FADEOUT, 300, STICKY, 1, OFFSETX, -20, CLOSEBTN, true, CLICKCLOSE, false, 278 BGCOLOR, '#F4FF91', TITLE, 'Entered:',TITLEBGCOLOR, '#F4FF91', TITLEFONTCOLOR, '#000000')!}, 279 $self->nbsp($correctAnswerPreview)) : ""; 280 $row .= $showAttemptResults ? CGI::td($self->nbsp($resultString)) : ""; 281 $row .= $showMessages ? CGI::td({-class=>"Message"},$self->nbsp($answerMessage)) : ""; 282 push @tableRows, $row; 283 } 284 285 # render equation images 286 $imgGen->render(refresh => 1); 287 288 # my $numIncorrectNoun = scalar @answerNames == 1 ? "question" : "questions"; 289 my $scorePercent = sprintf("%.0f%%", $problemResult->{score} * 100); 290 # FIXME -- I left the old code in in case we have to back out. 291 # my $summary = "On this attempt, you answered $numCorrect out of " 292 # . scalar @answerNames . " $numIncorrectNoun correct, for a score of $scorePercent."; 293 my $summary = ""; 294 unless (defined($problemResult->{summary}) and $problemResult->{summary} =~ /\S/) { 295 if (scalar @answerNames == 1) { #default messages 296 if ($numCorrect == scalar @answerNames) { 297 $summary .= CGI::div({class=>"ResultsWithoutError"},"The answer above is correct."); 298 } else { 299 $summary .= CGI::div({class=>"ResultsWithError"},"The answer above is NOT ${fully}correct."); 300 } 301 } else { 302 if ($numCorrect == scalar @answerNames) { 303 $summary .= CGI::div({class=>"ResultsWithoutError"},"All of the answers above are correct."); 304 } 305 unless ($numCorrect + $numBlanks == scalar( @answerNames)) { 306 $summary .= CGI::div({class=>"ResultsWithError"},"At least one of the answers above is NOT ${fully}correct."); 307 } 308 if ($numBlanks) { 309 my $s = ($numBlanks>1)?'':'s'; 310 $summary .= CGI::div({class=>"ResultsAlert"},"$numBlanks of the questions remain$s unanswered."); 311 } 312 } 313 } else { 314 $summary = $problemResult->{summary}; # summary has been defined by grader 315 } 316 317 $self->{correct_ids}=[@correct_ids] if @correct_ids; 318 $self->{incorrect_ids} = [@incorrect_ids] if @incorrect_ids; 319 320 return 321 CGI::table({-class=>"attemptResults"}, CGI::Tr(\@tableRows)) 322 . ($showSummary ? CGI::p({class=>'attemptResultsSummary'},$summary) : ""); 323 } 324 325 326 # Note: previewAnswer is lifted into GatewayQuiz.pm 327 328 sub previewAnswer { 329 my ($self, $answerResult, $imgGen, $tthPreambleCache) = @_; 330 my $ce = $self->r->ce; 331 my $effectiveUser = $self->{effectiveUser}; 332 my $set = $self->{set}; 333 my $problem = $self->{problem}; 334 my $displayMode = $self->{displayMode}; 335 336 # note: right now, we have to do things completely differently when we are 337 # rendering math from INSIDE the translator and from OUTSIDE the translator. 338 # so we'll just deal with each case explicitly here. there's some code 339 # duplication that can be dealt with later by abstracting out tth/dvipng/etc. 340 341 my $tex = $answerResult->{preview_latex_string}; 342 343 return "" unless defined $tex and $tex ne ""; 344 345 if ($displayMode eq "plainText") { 346 return $tex; 347 } elsif ($displayMode eq "formattedText") { 348 349 # read the TTH preamble, or use the cached copy passed in from the caller 350 my $tthPreamble=''; 351 if (defined $$tthPreambleCache) { 352 $tthPreamble = $$tthPreambleCache; 353 } else { 354 my $tthPreambleFile = $ce->{courseDirs}->{templates} . "/tthPreamble.tex"; 355 if (-r $tthPreambleFile) { 356 $tthPreamble = readFile($tthPreambleFile); 357 # thanks to Jim Martino. each line in the definition file should end with 358 #a % to prevent adding supurious paragraphs to output: 359 $tthPreamble =~ s/(.)\n/$1%\n/g; 360 # solves the problem if the file doesn't end with a return: 361 $tthPreamble .="%\n"; 362 # store preamble in cache: 363 $$tthPreambleCache = $tthPreamble; 364 } else { 365 } 366 } 367 368 # construct TTH command line 369 my $tthCommand = $ce->{externalPrograms}->{tth} 370 . " -L -f5 -u -r 2> /dev/null <<END_OF_INPUT; echo > /dev/null\n" 371 . $tthPreamble . "\\[" . $tex . "\\]\n" 372 . "END_OF_INPUT\n"; 373 374 # call tth 375 my $result = `$tthCommand`; 376 if ($?) { 377 return "<b>[tth failed: $? $@]</b>"; 378 } else { 379 # avoid border problems in tables and remove unneeded initial <br> 380 $result =~ s/(<table [^>]*)>/$1 CLASS="ArrayLayout">/gi; 381 $result =~ s!\s*<br clear="all" />!!; 382 return $result; 383 } 384 385 } elsif ($displayMode eq "images") { 386 $imgGen->add($tex); 387 } elsif ($displayMode eq "MathJax") { 388 return '<span class="MathJax_Preview">[math]</span><script type="math/tex; mode=display">'.$tex.'</script>'; 389 } elsif ($displayMode eq "jsMath") { 390 $tex =~ s/&/&/g; $tex =~ s/</</g; $tex =~ s/>/>/g; 391 return '<SPAN CLASS="math">\\displaystyle{'.$tex.'}</SPAN>'; 392 } 393 } 394 sub previewCorrectAnswer { 395 my ($self, $answerResult, $imgGen, $tthPreambleCache) = @_; 396 my $ce = $self->r->ce; 397 my $effectiveUser = $self->{effectiveUser}; 398 my $set = $self->{set}; 399 my $problem = $self->{problem}; 400 my $displayMode = $self->{displayMode}; 401 402 # note: right now, we have to do things completely differently when we are 403 # rendering math from INSIDE the translator and from OUTSIDE the translator. 404 # so we'll just deal with each case explicitly here. there's some code 405 # duplication that can be dealt with later by abstracting out tth/dvipng/etc. 406 407 my $tex = $answerResult->{correct_ans_latex_string}; 408 return $answerResult->{correct_ans} unless defined $tex and $tex=~/\S/; # some answers don't have latex strings defined 409 # return "" unless defined $tex and $tex ne ""; 410 411 if ($displayMode eq "plainText") { 412 return $tex; 413 } elsif ($displayMode eq "formattedText") { 414 415 # read the TTH preamble, or use the cached copy passed in from the caller 416 my $tthPreamble=''; 417 if (defined $$tthPreambleCache) { 418 $tthPreamble = $$tthPreambleCache; 419 } else { 420 my $tthPreambleFile = $ce->{courseDirs}->{templates} . "/tthPreamble.tex"; 421 if (-r $tthPreambleFile) { 422 $tthPreamble = readFile($tthPreambleFile); 423 # thanks to Jim Martino. each line in the definition file should end with 424 #a % to prevent adding supurious paragraphs to output: 425 $tthPreamble =~ s/(.)\n/$1%\n/g; 426 # solves the problem if the file doesn't end with a return: 427 $tthPreamble .="%\n"; 428 # store preamble in cache: 429 $$tthPreambleCache = $tthPreamble; 430 } else { 431 } 432 } 433 434 # construct TTH command line 435 my $tthCommand = $ce->{externalPrograms}->{tth} 436 . " -L -f5 -u -r 2> /dev/null <<END_OF_INPUT; echo > /dev/null\n" 437 . $tthPreamble . "\\[" . $tex . "\\]\n" 438 . "END_OF_INPUT\n"; 439 440 # call tth 441 my $result = `$tthCommand`; 442 if ($?) { 443 return "<b>[tth failed: $? $@]</b>"; 444 } else { 445 # avoid border problems in tables and remove unneeded initial <br> 446 $result =~ s/(<table [^>]*)>/$1 CLASS="ArrayLayout">/gi; 447 $result =~ s!\s*<br clear="all" />!!; 448 return $result; 449 } 450 451 } elsif ($displayMode eq "images") { 452 $imgGen->add($tex); 453 } elsif ($displayMode eq "MathJax") { 454 return '<span class="MathJax_Preview">[math]</span><script type="math/tex; mode=display">'.$tex.'</script>'; 455 } elsif ($displayMode eq "jsMath") { 456 $tex =~ s/&/&/g; $tex =~ s/</</g; $tex =~ s/>/>/g; 457 return '<SPAN CLASS="math">\\displaystyle{'.$tex.'}</SPAN>'; 458 } 459 } 460 461 ################################################################################ 462 # Template escape implementations 463 ################################################################################ 464 465 sub pre_header_initialize { 466 my ($self) = @_; 467 my $r = $self->r; 468 my $ce = $r->ce; 469 my $db = $r->db; 470 my $authz = $r->authz; 471 my $urlpath = $r->urlpath; 472 473 my $setName = $urlpath->arg("setID"); 474 my $problemNumber = $r->urlpath->arg("problemID"); 475 my $userName = $r->param('user'); 476 my $effectiveUserName = $r->param('effectiveUser'); 477 my $key = $r->param('key'); 478 my $editMode = $r->param("editMode"); 479 480 my $user = $db->getUser($userName); # checked 481 die "record for user $userName (real user) does not exist." 482 unless defined $user; 483 484 my $effectiveUser = $db->getUser($effectiveUserName); # checked 485 die "record for user $effectiveUserName (effective user) does not exist." 486 unless defined $effectiveUser; 487 488 # obtain the merged set for $effectiveUser 489 my $set = $db->getMergedSet($effectiveUserName, $setName); # checked 490 491 $self->set_showOldAnswers_default($ce, $userName, $authz, $set); 492 493 # Database fix (in case of undefined visiblity state values) 494 # this is only necessary because some people keep holding to ww1.9 which did not have a visible field 495 # make sure visible is set to 0 or 1 496 if ( $set and $set->visible ne "0" and $set->visible ne "1") { 497 my $globalSet = $db->getGlobalSet($set->set_id); 498 $globalSet->visible("1"); # defaults to visible 499 $db->putGlobalSet($globalSet); 500 $set = $db->getMergedSet($effectiveUserName, $setName); 501 } else { 502 # don't do anything just yet, maybe we're a professor and we're 503 # fabricating a set or haven't assigned it to ourselves just yet 504 } 505 # When a set is created enable_reduced_scoring is null, so we have to set it 506 if ( $set and $set->enable_reduced_scoring ne "0" and $set->enable_reduced_scoring ne "1") { 507 my $globalSet = $db->getGlobalSet($set->set_id); 508 $globalSet->enable_reduced_scoring("0"); # defaults to disabled 509 $db->putGlobalSet($globalSet); 510 $set = $db->getMergedSet($effectiveUserName, $setName); 511 } 512 513 514 # obtain the merged problem for $effectiveUser 515 my $problem = $db->getMergedProblem($effectiveUserName, $setName, $problemNumber); # checked 516 517 if ($authz->hasPermissions($userName, "modify_problem_sets")) { 518 # professors are allowed to fabricate sets and problems not 519 # assigned to them (or anyone). this allows them to use the 520 # editor to 521 522 # if a User Set does not exist for this user and this set 523 # then we check the Global Set 524 # if that does not exist we create a fake set 525 # if it does, we add fake user data 526 unless (defined $set) { 527 my $userSetClass = $db->{set_user}->{record}; 528 my $globalSet = $db->getGlobalSet($setName); # checked 529 530 if (not defined $globalSet) { 531 $set = fake_set($db); 532 } else { 533 $set = global2user($userSetClass, $globalSet); 534 $set->psvn(0); 535 } 536 } 537 538 # if that is not yet defined obtain the global problem, 539 # convert it to a user problem, and add fake user data 540 unless (defined $problem) { 541 my $userProblemClass = $db->{problem_user}->{record}; 542 my $globalProblem = $db->getGlobalProblem($setName, $problemNumber); # checked 543 # if the global problem doesn't exist either, bail! 544 if(not defined $globalProblem) { 545 my $sourceFilePath = $r->param("sourceFilePath"); 546 die "sourceFilePath is unsafe!" unless path_is_subdir($sourceFilePath, $ce->{courseDirs}->{templates}, 1); # 1==path can be relative to dir 547 # These are problems from setmaker. If declared invalid, they won't come up 548 $self->{invalidProblem} = $self->{invalidSet} = 1 unless defined $sourceFilePath; 549 # die "Problem $problemNumber in set $setName does not exist" unless defined $sourceFilePath; 550 $problem = fake_problem($db); 551 $problem->problem_id(1); 552 $problem->source_file($sourceFilePath); 553 $problem->user_id($effectiveUserName); 554 } else { 555 $problem = global2user($userProblemClass, $globalProblem); 556 $problem->user_id($effectiveUserName); 557 $problem->problem_seed(0); 558 $problem->status(0); 559 $problem->attempted(0); 560 $problem->last_answer(""); 561 $problem->num_correct(0); 562 $problem->num_incorrect(0); 563 } 564 } 565 566 # now we're sure we have valid UserSet and UserProblem objects 567 # yay! 568 569 # now deal with possible editor overrides: 570 571 # if the caller is asking to override the source file, and 572 # editMode calls for a temporary file, do so 573 my $sourceFilePath = $r->param("sourceFilePath"); 574 if (defined $editMode and $editMode eq "temporaryFile" and defined $sourceFilePath) { 575 die "sourceFilePath is unsafe!" unless path_is_subdir($sourceFilePath, $ce->{courseDirs}->{templates}, 1); # 1==path can be relative to dir 576 $problem->source_file($sourceFilePath); 577 } 578 579 # if the problem does not have a source file or no source file has been passed in 580 # then this is really an invalid problem (probably from a bad URL) 581 $self->{invalidProblem} = not (defined $sourceFilePath or $problem->source_file); 582 583 # if the caller is asking to override the problem seed, do so 584 my $problemSeed = $r->param("problemSeed"); 585 if (defined $problemSeed) { 586 $problem->problem_seed($problemSeed); 587 } 588 589 my $visiblityStateClass = ($set->visible) ? "visible" : "hidden"; 590 my $visiblityStateText = ($set->visible) ? "visible to students." : "hidden from students."; 591 $self->addmessage(CGI::span("This set is " . CGI::font({class=>$visiblityStateClass}, $visiblityStateText))); 592 593 # test for additional problem validity if it's not already invalid 594 } else { 595 $self->{invalidProblem} = !(defined $problem and ($set->visible || $authz->hasPermissions($userName, "view_hidden_sets"))); 596 597 $self->addbadmessage(CGI::p("This problem will not count towards your grade.")) if $problem and not $problem->value and not $self->{invalidProblem}; 598 } 599 600 $self->{userName} = $userName; 601 $self->{effectiveUserName} = $effectiveUserName; 602 $self->{user} = $user; 603 $self->{effectiveUser} = $effectiveUser; 604 $self->{set} = $set; 605 $self->{problem} = $problem; 606 $self->{editMode} = $editMode; 607 608 ##### form processing ##### 609 610 # set options from form fields (see comment at top of file for names) 611 my $displayMode = $r->param("displayMode") || $ce->{pg}->{options}->{displayMode}; 612 my $redisplay = $r->param("redisplay"); 613 my $submitAnswers = $r->param("submitAnswers"); 614 my $checkAnswers = $r->param("checkAnswers"); 615 my $previewAnswers = $r->param("previewAnswers"); 616 617 my $formFields = { WeBWorK::Form->new_from_paramable($r)->Vars }; 618 619 $self->{displayMode} = $displayMode; 620 $self->{redisplay} = $redisplay; 621 $self->{submitAnswers} = $submitAnswers; 622 $self->{checkAnswers} = $checkAnswers; 623 $self->{previewAnswers} = $previewAnswers; 624 $self->{formFields} = $formFields; 625 626 # get result and send to message 627 my $status_message = $r->param("status_message"); 628 $self->addmessage(CGI::p("$status_message")) if $status_message; 629 630 # now that we've set all the necessary variables quit out if the set or problem is invalid 631 return if $self->{invalidSet} || $self->{invalidProblem}; 632 633 ##### permissions ##### 634 635 # what does the user want to do? 636 #FIXME There is a problem with checkboxes -- if they are not checked they are invisible. Hence if the default mode in $ce is 1 637 # there is no way to override this. Probably this is ok for the last three options, but it was definitely not ok for showing 638 # saved answers which is normally on, but you want to be able to turn it off! This section should be moved to ContentGenerator 639 # so that you can set these options anywhere. We also need mechanisms for making them sticky. 640 # Note: ProblemSet and ProblemSets might set showOldAnswers to '', which 641 # needs to be treated as if it is not set. 642 my %want = ( 643 showOldAnswers => (defined($r->param("showOldAnswers")) and $r->param("showOldAnswers") ne '') ? $r->param("showOldAnswers") : $ce->{pg}->{options}->{showOldAnswers}, 644 showCorrectAnswers => $r->param("showCorrectAnswers") || $ce->{pg}->{options}->{showCorrectAnswers}, 645 showHints => $r->param("showHints") || $ce->{pg}->{options}->{showHints}, 646 showSolutions => $r->param("showSolutions") || $ce->{pg}->{options}->{showSolutions}, 647 recordAnswers => $submitAnswers, 648 checkAnswers => $checkAnswers, 649 getSubmitButton => 1, 650 ); 651 652 # are certain options enforced? 653 my %must = ( 654 showOldAnswers => 0, 655 showCorrectAnswers => 0, 656 showHints => 0, 657 showSolutions => 0, 658 recordAnswers => ! $authz->hasPermissions($userName, "avoid_recording_answers"), 659 checkAnswers => 0, 660 getSubmitButton => 0, 661 ); 662 663 # does the user have permission to use certain options? 664 my @args = ($user, $effectiveUser, $set, $problem); 665 my %can = ( 666 showOldAnswers => $self->can_showOldAnswers(@args), 667 showCorrectAnswers => $self->can_showCorrectAnswers(@args), 668 showHints => $self->can_showHints(@args), 669 showSolutions => $self->can_showSolutions(@args), 670 recordAnswers => $self->can_recordAnswers(@args, 0), 671 checkAnswers => $self->can_checkAnswers(@args, $submitAnswers), 672 getSubmitButton => $self->can_recordAnswers(@args, $submitAnswers), 673 ); 674 675 # final values for options 676 my %will; 677 foreach (keys %must) { 678 $will{$_} = $can{$_} && ($want{$_} || $must{$_}); 679 #warn "final values for options $_ is can $can{$_}, want $want{$_}, must $must{$_}, will $will{$_}"; 680 } 681 682 ##### sticky answers ##### 683 684 if (not ($submitAnswers or $previewAnswers or $checkAnswers) and $will{showOldAnswers}) { 685 # do this only if new answers are NOT being submitted 686 my %oldAnswers = decodeAnswers($problem->last_answer); 687 $formFields->{$_} = $oldAnswers{$_} foreach keys %oldAnswers; 688 } 689 690 ##### translation ##### 691 692 debug("begin pg processing"); 693 my $pg = WeBWorK::PG->new( 694 $ce, 695 $effectiveUser, 696 $key, 697 $set, 698 $problem, 699 $set->psvn, # FIXME: this field should be removed 700 $formFields, 701 { # translation options 702 displayMode => $displayMode, 703 showHints => $will{showHints}, 704 showSolutions => $will{showSolutions}, 705 refreshMath2img => $will{showHints} || $will{showSolutions}, 706 processAnswers => 1, 707 permissionLevel => $db->getPermissionLevel($userName)->permission, 708 effectivePermissionLevel => $db->getPermissionLevel($effectiveUserName)->permission, 709 }, 710 ); 711 712 debug("end pg processing"); 713 714 ##### fix hint/solution options ##### 715 716 $can{showHints} &&= $pg->{flags}->{hintExists} 717 &&= $pg->{flags}->{showHintLimit}<=$pg->{state}->{num_of_incorrect_ans}; 718 $can{showSolutions} &&= $pg->{flags}->{solutionExists}; 719 720 ##### store fields ##### 721 722 $self->{want} = \%want; 723 $self->{must} = \%must; 724 $self->{can} = \%can; 725 $self->{will} = \%will; 726 $self->{pg} = $pg; 727 } 728 729 sub if_errors($$) { 730 my ($self, $arg) = @_; 731 732 if ($self->{isOpen}) { 733 return $self->{pg}->{flags}->{error_flag} ? $arg : !$arg; 734 } else { 735 return !$arg; 736 } 737 } 738 739 sub head { 740 my ($self) = @_; 741 742 return "" if ( $self->{invalidSet} ); 743 return $self->{pg}->{head_text} if $self->{pg}->{head_text}; 744 } 745 746 sub options { 747 my ($self) = @_; 748 #warn "doing options in Problem"; 749 750 # don't show options if we don't have anything to show 751 return "" if $self->{invalidSet} or $self->{invalidProblem}; 752 753 my $displayMode = $self->{displayMode}; 754 my %can = %{ $self->{can} }; 755 756 my @options_to_show = "displayMode"; 757 push @options_to_show, "showOldAnswers" if $can{showOldAnswers}; 758 push @options_to_show, "showHints" if $can{showHints}; 759 push @options_to_show, "showSolutions" if $can{showSolutions}; 760 761 return $self->optionsMacro( 762 options_to_show => \@options_to_show, 763 extra_params => ["editMode", "sourceFilePath"], 764 ); 765 } 766 767 sub siblings { 768 my ($self) = @_; 769 my $r = $self->r; 770 my $db = $r->db; 771 my $urlpath = $r->urlpath; 772 773 # can't show sibling problems if the set is invalid 774 return "" if $self->{invalidSet}; 775 776 my $courseID = $urlpath->arg("courseID"); 777 my $setID = $self->{set}->set_id; 778 my $eUserID = $r->param("effectiveUser"); 779 my @problemIDs = sort { $a <=> $b } $db->listUserProblems($eUserID, $setID); 780 781 print CGI::start_div({class=>"info-box", id=>"fisheye"}); 782 print CGI::h2("Problems"); 783 #print CGI::start_ul({class=>"LinksMenu"}); 784 #print CGI::start_li(); 785 #print CGI::span({style=>"font-size:larger"}, "Problems"); 786 print CGI::start_ul(); 787 788 foreach my $problemID (@problemIDs) { 789 my $problemPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Problem", 790 courseID => $courseID, setID => $setID, problemID => $problemID); 791 print CGI::li(CGI::a( {href=>$self->systemLink($problemPage, 792 params=>{ displayMode => $self->{displayMode}, 793 showOldAnswers => $self->{will}->{showOldAnswers} 794 })}, "Problem $problemID") 795 ); 796 } 797 798 print CGI::end_ul(); 799 #print CGI::end_li(); 800 #print CGI::end_ul(); 801 print CGI::end_div(); 802 803 return ""; 804 } 805 806 sub nav { 807 my ($self, $args) = @_; 808 my $r = $self->r; 809 my $db = $r->db; 810 my $urlpath = $r->urlpath; 811 812 return "" if ( $self->{invalidSet} ); 813 814 my $courseID = $urlpath->arg("courseID"); 815 my $setID = $self->{set}->set_id if !($self->{invalidSet}); 816 my $problemID = $self->{problem}->problem_id if !($self->{invalidProblem}); 817 my $eUserID = $r->param("effectiveUser"); 818 819 my ($prevID, $nextID); 820 821 if (!$self->{invalidProblem}) { 822 my @problemIDs = $db->listUserProblems($eUserID, $setID); 823 foreach my $id (@problemIDs) { 824 $prevID = $id if $id < $problemID 825 and (not defined $prevID or $id > $prevID); 826 $nextID = $id if $id > $problemID 827 and (not defined $nextID or $id < $nextID); 828 } 829 } 830 831 my @links; 832 833 if ($prevID) { 834 my $prevPage = $urlpath->newFromModule(__PACKAGE__, 835 courseID => $courseID, setID => $setID, problemID => $prevID); 836 push @links, "Previous Problem", $r->location . $prevPage->path, "navPrev"; 837 } else { 838 push @links, "Previous Problem", "", "navPrevGrey"; 839 } 840 841 if (defined($setID) && $setID ne 'Undefined_Set') { 842 push @links, "Problem List", $r->location . $urlpath->parent->path, "navProbList"; 843 } else { 844 push @links, "Problem List", "", "navProbListGrey"; 845 } 846 847 if ($nextID) { 848 my $nextPage = $urlpath->newFromModule(__PACKAGE__, 849 courseID => $courseID, setID => $setID, problemID => $nextID); 850 push @links, "Next Problem", $r->location . $nextPage->path, "navNext"; 851 } else { 852 push @links, "Next Problem", "", "navNextGrey"; 853 } 854 855 my $tail = ""; 856 857 $tail .= "&displayMode=".$self->{displayMode} if defined $self->{displayMode}; 858 $tail .= "&showOldAnswers=".$self->{will}->{showOldAnswers} 859 if defined $self->{will}->{showOldAnswers}; 860 return $self->navMacro($args, $tail, @links); 861 } 862 863 sub title { 864 my ($self) = @_; 865 866 # using the url arguments won't break if the set/problem are invalid 867 my $setID = WeBWorK::ContentGenerator::underscore2nbsp($self->r->urlpath->arg("setID")); 868 my $problemID = $self->r->urlpath->arg("problemID"); 869 870 return "$setID: Problem $problemID"; 871 } 872 873 sub body { 874 my $self = shift; 875 my $r = $self->r; 876 my $ce = $r->ce; 877 my $db = $r->db; 878 my $authz = $r->authz; 879 my $urlpath = $r->urlpath; 880 my $user = $r->param('user'); 881 my $effectiveUser = $r->param('effectiveUser'); 882 if ( $self->{invalidSet} ) { 883 return CGI::div({class=>"ResultsWithError"}, 884 CGI::p("The selected problem set (" . 885 $urlpath->arg("setID") . ") is not " . 886 "a valid set for $effectiveUser:"), 887 CGI::p($self->{invalidSet})); 888 } 889 890 if ($self->{invalidProblem}) { 891 return CGI::div({class=>"ResultsWithError"}, 892 CGI::p("The selected problem (" . $urlpath->arg("problemID") . ") is not a valid problem for set " . $self->{set}->set_id . ".")); 893 } 894 895 # unpack some useful variables 896 my $set = $self->{set}; 897 my $problem = $self->{problem}; 898 my $editMode = $self->{editMode}; 899 my $submitAnswers = $self->{submitAnswers}; 900 my $checkAnswers = $self->{checkAnswers}; 901 my $previewAnswers = $self->{previewAnswers}; 902 my %want = %{ $self->{want} }; 903 my %can = %{ $self->{can} }; 904 my %must = %{ $self->{must} }; 905 my %will = %{ $self->{will} }; 906 my $pg = $self->{pg}; 907 908 my $courseName = $urlpath->arg("courseID"); 909 910 # FIXME: move editor link to top, next to problem number. 911 # format as "[edit]" like we're doing with course info file, etc. 912 # add edit link for set as well. 913 my $editorLink = ""; 914 # if we are here without a real homework set, carry that through 915 my $forced_field = []; 916 $forced_field = ['sourceFilePath' => $r->param("sourceFilePath")] if 917 ($set->set_id eq 'Undefined_Set'); 918 if ($authz->hasPermissions($user, "modify_problem_sets")) { 919 my $editorPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::PGProblemEditor", 920 courseID => $courseName, setID => $set->set_id, problemID => $problem->problem_id); 921 my $editorURL = $self->systemLink($editorPage, params=>$forced_field); 922 $editorLink = CGI::p(CGI::a({href=>$editorURL,target =>'WW_Editor'}, "Edit this problem")); 923 } 924 925 ##### translation errors? ##### 926 927 if ($pg->{flags}->{error_flag}) { 928 if ($authz->hasPermissions($user, "view_problem_debugging_info")) { 929 print $self->errorOutput($pg->{errors}, $pg->{body_text}); 930 } else { 931 print $self->errorOutput($pg->{errors}, "You do not have permission to view the details of this error."); 932 } 933 print $editorLink; 934 return ""; 935 } 936 937 ##### answer processing ##### 938 debug("begin answer processing"); 939 # if answers were submitted: 940 my $scoreRecordedMessage; 941 my $pureProblem; 942 if ($submitAnswers) { 943 # get a "pure" (unmerged) UserProblem to modify 944 # this will be undefined if the problem has not been assigned to this user 945 $pureProblem = $db->getUserProblem($problem->user_id, $problem->set_id, $problem->problem_id); # checked 946 if (defined $pureProblem) { 947 # store answers in DB for sticky answers 948 my %answersToStore; 949 my %answerHash = %{ $pg->{answers} }; 950 $answersToStore{$_} = $self->{formFields}->{$_} #$answerHash{$_}->{original_student_ans} -- this may have been modified for fields with multiple values. Don't use it!! 951 foreach (keys %answerHash); 952 953 # There may be some more answers to store -- one which are auxiliary entries to a primary answer. Evaluating 954 # matrices works in this way, only the first answer triggers an answer evaluator, the rest are just inputs 955 # however we need to store them. Fortunately they are still in the input form. 956 my @extra_answer_names = @{ $pg->{flags}->{KEPT_EXTRA_ANSWERS}}; 957 $answersToStore{$_} = $self->{formFields}->{$_} foreach (@extra_answer_names); 958 959 # Now let's encode these answers to store them -- append the extra answers to the end of answer entry order 960 my @answer_order = (@{$pg->{flags}->{ANSWER_ENTRY_ORDER}}, @extra_answer_names); 961 my $answerString = encodeAnswers(%answersToStore, 962 @answer_order); 963 964 # store last answer to database 965 $problem->last_answer($answerString); 966 $pureProblem->last_answer($answerString); 967 $db->putUserProblem($pureProblem); 968 969 # store state in DB if it makes sense 970 if ($will{recordAnswers}) { 971 $problem->status($pg->{state}->{recorded_score}); 972 $problem->sub_status($pg->{state}->{sub_recorded_score}); 973 $problem->attempted(1); 974 $problem->num_correct($pg->{state}->{num_of_correct_ans}); 975 $problem->num_incorrect($pg->{state}->{num_of_incorrect_ans}); 976 $pureProblem->status($pg->{state}->{recorded_score}); 977 $pureProblem->sub_status($pg->{state}->{sub_recorded_score}); 978 $pureProblem->attempted(1); 979 $pureProblem->num_correct($pg->{state}->{num_of_correct_ans}); 980 $pureProblem->num_incorrect($pg->{state}->{num_of_incorrect_ans}); 981 if ($db->putUserProblem($pureProblem)) { 982 $scoreRecordedMessage = "Your score was recorded."; 983 } else { 984 $scoreRecordedMessage = "Your score was not recorded because there was a failure in storing the problem record to the database."; 985 } 986 # write to the transaction log, just to make sure 987 writeLog($self->{ce}, "transaction", 988 $problem->problem_id."\t". 989 $problem->set_id."\t". 990 $problem->user_id."\t". 991 $problem->source_file."\t". 992 $problem->value."\t". 993 $problem->max_attempts."\t". 994 $problem->problem_seed."\t". 995 $pureProblem->status."\t". 996 $pureProblem->attempted."\t". 997 $pureProblem->last_answer."\t". 998 $pureProblem->num_correct."\t". 999 $pureProblem->num_incorrect 1000 ); 1001 } else { 1002 if (before($set->open_date) or after($set->due_date)) { 1003 $scoreRecordedMessage = "Your score was not recorded because this homework set is closed."; 1004 } else { 1005 $scoreRecordedMessage = "Your score was not recorded."; 1006 } 1007 } 1008 } else { 1009 $scoreRecordedMessage = "Your score was not recorded because this problem has not been assigned to you."; 1010 } 1011 } 1012 1013 # logging student answers 1014 1015 my $answer_log = $self->{ce}->{courseFiles}->{logs}->{'answer_log'}; 1016 if ( defined($answer_log ) and defined($pureProblem)) { 1017 if ($submitAnswers && !$authz->hasPermissions($effectiveUser, "dont_log_past_answers")) { 1018 my $answerString = ""; my $scores = ""; 1019 my %answerHash = %{ $pg->{answers} }; 1020 # FIXME this is the line 552 error. make sure original student ans is defined. 1021 # The fact that it is not defined is probably due to an error in some answer evaluator. 1022 # But I think it is useful to suppress this error message in the log. 1023 foreach (sortByName(undef, keys %answerHash)) { 1024 my $orig_ans = $answerHash{$_}->{original_student_ans}; 1025 my $student_ans = defined $orig_ans ? $orig_ans : ''; 1026 $answerString .= $student_ans."\t"; 1027 $scores .= $answerHash{$_}->{score} >= 1 ? "1" : "0"; 1028 } 1029 $answerString = '' unless defined($answerString); # insure string is defined. 1030 writeCourseLog($self->{ce}, "answer_log", 1031 join("", 1032 '|', $problem->user_id, 1033 '|', $problem->set_id, 1034 '|', $problem->problem_id, 1035 '|', $scores, "\t", 1036 time(),"\t", 1037 $answerString, 1038 ), 1039 ); 1040 1041 } 1042 } 1043 1044 debug("end answer processing"); 1045 ##### javaScripts ############# 1046 my $site_url = $ce->{webworkURLs}->{htdocs}; 1047 print CGI::start_script({type=>"text/javascript", src=>"$site_url/js/wz_tooltip.js"}), CGI::end_script(); 1048 1049 ##### output ##### 1050 # custom message for editor 1051 if ($authz->hasPermissions($user, "modify_problem_sets") and defined $editMode) { 1052 if ($editMode eq "temporaryFile") { 1053 print CGI::p(CGI::div({class=>'temporaryFile'}, "Viewing temporary file: ", $problem->source_file)); 1054 } elsif ($editMode eq "savedFile") { 1055 # taken care of in the initialization phase 1056 } 1057 } 1058 print CGI::start_div({class=>"problemHeader"}); 1059 1060 1061 1062 # attempt summary 1063 #FIXME -- the following is a kludge: if showPartialCorrectAnswers is negative don't show anything. 1064 # until after the due date 1065 # do I need to check $will{showCorrectAnswers} to make preflight work?? 1066 if (($pg->{flags}->{showPartialCorrectAnswers} >= 0 and $submitAnswers) ) { 1067 # print this if user submitted answers OR requested correct answers 1068 1069 print $self->attemptResults($pg, 1, 1070 $will{showCorrectAnswers}, 1071 $pg->{flags}->{showPartialCorrectAnswers}, 1, 1); 1072 } elsif ($checkAnswers) { 1073 # print this if user previewed answers 1074 print CGI::div({class=>'ResultsWithError'},"ANSWERS ONLY CHECKED -- ANSWERS NOT RECORDED"), CGI::br(); 1075 print $self->attemptResults($pg, 1, $will{showCorrectAnswers}, 1, 1, 1); 1076 # show attempt answers 1077 # show correct answers if asked 1078 # show attempt results (correctness) 1079 # show attempt previews 1080 } elsif ($previewAnswers) { 1081 # print this if user previewed answers 1082 print CGI::div({class=>'ResultsWithError'},"PREVIEW ONLY -- ANSWERS NOT RECORDED"),CGI::br(),$self->attemptResults($pg, 1, 0, 0, 0, 1); 1083 # show attempt answers 1084 # don't show correct answers 1085 # don't show attempt results (correctness) 1086 # show attempt previews 1087 } 1088 1089 print CGI::end_div(); 1090 1091 1092 ########################### 1093 # print style sheet for correct and incorrect answers 1094 ########################### 1095 1096 print CGI::start_style({type=>"text/css"}); 1097 print '#'.join(', #', @{ $self->{correct_ids} }), "{background-color:#8F8;}" if ref( $self->{correct_ids} )=~/ARRAY/; #green 1098 print '#'.join(', #', @{ $self->{incorrect_ids} }), "{background-color:#FA0;}" if ref( $self->{incorrect_ids})=~/ARRAY/; #orange 1099 print CGI::end_style(); 1100 1101 ########################### 1102 # main form 1103 ########################### 1104 print "\n"; 1105 print CGI::start_form(-method=>"POST", -action=> $r->uri,-name=>"problemMainForm", onsubmit=>"submitAction()"); 1106 print $self->hidden_authen_fields; 1107 print "\n"; 1108 print CGI::start_div({class=>"problem"}); 1109 print CGI::p($pg->{body_text}); 1110 print CGI::p(CGI::b("Note: "). CGI::i($pg->{result}->{msg})) if $pg->{result}->{msg}; 1111 print $editorLink; # this is empty unless it is appropriate to have an editor link. 1112 print CGI::end_div(); 1113 1114 print CGI::start_p(); 1115 1116 if ($can{showCorrectAnswers}) { 1117 print CGI::checkbox( 1118 -name => "showCorrectAnswers", 1119 -checked => $will{showCorrectAnswers}, 1120 -label => "Show correct answers", 1121 -value => 1, 1122 ); 1123 } 1124 if ($can{showHints}) { 1125 print CGI::div({style=>"color:red"}, 1126 CGI::checkbox( 1127 -name => "showHints", 1128 -checked => $will{showHints}, 1129 -label => "Show Hints", 1130 -value =>1, 1131 ) 1132 ); 1133 } 1134 if ($can{showSolutions}) { 1135 print CGI::checkbox( 1136 -name => "showSolutions", 1137 -checked => $will{showSolutions}, 1138 -label => "Show Solutions", 1139 -value => 1, 1140 ); 1141 } 1142 1143 if ($can{showCorrectAnswers} or $can{showHints} or $can{showSolutions}) { 1144 print CGI::br(); 1145 } 1146 1147 print CGI::submit(-name=>"previewAnswers", -label=>"Preview Answers"); 1148 if ($can{checkAnswers}) { 1149 print CGI::submit(-name=>"checkAnswers", -label=>"Check Answers"); 1150 } 1151 if ($can{getSubmitButton}) { 1152 if ($user ne $effectiveUser) { 1153 # if acting as a student, make it clear that answer submissions will 1154 # apply to the student's records, not the professor's. 1155 print CGI::submit(-name=>"submitAnswers", -label=>"Submit Answers for $effectiveUser"); 1156 } else { 1157 #print CGI::submit(-name=>"submitAnswers", -label=>"Submit Answers", -onclick=>"alert('submit button clicked')"); 1158 print CGI::submit(-name=>"submitAnswers", -label=>"Submit Answers", -onclick=>""); 1159 # FIXME for unknown reasons the -onclick label seems to have to be there in order to allow the forms onsubmit to trigger 1160 # WFT??? 1161 } 1162 } 1163 1164 print CGI::end_p(); 1165 1166 print CGI::start_div({class=>"scoreSummary"}); 1167 1168 # score summary 1169 my $attempts = $problem->num_correct + $problem->num_incorrect; 1170 my $attemptsNoun = $attempts != 1 ? "times" : "time"; 1171 my $problem_status = $problem->status || 0; 1172 my $lastScore = sprintf("%.0f%%", $problem_status * 100); # Round to whole number 1173 my ($attemptsLeft, $attemptsLeftNoun); 1174 if ($problem->max_attempts == -1) { 1175 # unlimited attempts 1176 $attemptsLeft = "unlimited"; 1177 $attemptsLeftNoun = "attempts"; 1178 } else { 1179 $attemptsLeft = $problem->max_attempts - $attempts; 1180 $attemptsLeftNoun = $attemptsLeft == 1 ? "attempt" : "attempts"; 1181 } 1182 1183 my $setClosed = 0; 1184 my $setClosedMessage; 1185 if (before($set->open_date) or after($set->due_date)) { 1186 $setClosed = 1; 1187 if (before($set->open_date)) { 1188 $setClosedMessage = "This homework set is not yet open."; 1189 } elsif (after($set->due_date)) { 1190 $setClosedMessage = "This homework set is closed."; 1191 } 1192 } 1193 #if (before($set->open_date) or after($set->due_date)) { 1194 # $setClosed = 1; 1195 # $setClosedMessage = "This homework set is closed."; 1196 # if ($authz->hasPermissions($user, "view_answers")) { 1197 # $setClosedMessage .= " However, since you are a privileged user, additional attempts will be recorded."; 1198 # } else { 1199 # $setClosedMessage .= " Additional attempts will not be recorded."; 1200 # } 1201 #} 1202 unless (defined( $pg->{state}->{state_summary_msg}) and $pg->{state}->{state_summary_msg}=~/\S/) { 1203 my $notCountedMessage = ($problem->value) ? "" : "(This problem will not count towards your grade.)"; 1204 print CGI::p(join("", 1205 $submitAnswers ? $scoreRecordedMessage . CGI::br() : "", 1206 "You have attempted this problem $attempts $attemptsNoun.", CGI::br(), 1207 $submitAnswers ?"You received a score of ".sprintf("%.0f%%", $pg->{result}->{score} * 100)." for this attempt.".CGI::br():'', 1208 $problem->attempted 1209 ? "Your overall recorded score is $lastScore. $notCountedMessage" . CGI::br() 1210 : "", 1211 $setClosed ? $setClosedMessage : "You have $attemptsLeft $attemptsLeftNoun remaining." 1212 )); 1213 }else { 1214 print CGI::p($pg->{state}->{state_summary_msg}); 1215 } 1216 1217 print CGI::end_div(); 1218 print CGI::start_div(); 1219 1220 my $pgdebug = join(CGI::br(), @{$pg->{pgcore}->{flags}->{DEBUG_messages}} ); 1221 my $pgwarning = join(CGI::br(), @{$pg->{pgcore}->{flags}->{WARNING_messages}} ); 1222 my $pginternalerrors = join(CGI::br(), @{$pg->{pgcore}->get_internal_debug_messages} ); 1223 my $pgerrordiv = $pgdebug||$pgwarning||$pginternalerrors; # is 1 if any of these are non-empty 1224 1225 print CGI::p({style=>"color:red;"}, "Checking additional error messages") if $pgerrordiv ; 1226 print CGI::p("pg debug<br/> $pgdebug" ) if $pgdebug ; 1227 print CGI::p("pg warning<br/>$pgwarning" ) if $pgwarning ; 1228 print CGI::p("pg internal errors<br/> $pginternalerrors") if $pginternalerrors; 1229 print CGI::end_div() if $pgerrordiv ; 1230 1231 # save state for viewOptions 1232 print CGI::hidden( 1233 -name => "showOldAnswers", 1234 -value => $will{showOldAnswers} 1235 ), 1236 1237 CGI::hidden( 1238 -name => "displayMode", 1239 -value => $self->{displayMode} 1240 ); 1241 print( CGI::hidden( 1242 -name => 'editMode', 1243 -value => $self->{editMode}, 1244 ) 1245 ) if defined($self->{editMode}) and $self->{editMode} eq 'temporaryFile'; 1246 1247 # this is a security risk -- students can use this to find the source code for the problem 1248 1249 my $permissionLevel = $db->getPermissionLevel($user)->permission; 1250 my $professorPermissionLevel = $ce->{userRoles}->{professor}; 1251 print( CGI::hidden( 1252 -name => 'sourceFilePath', 1253 -value => $self->{problem}->{source_file} 1254 )) if defined($self->{problem}->{source_file}) and $permissionLevel>= $professorPermissionLevel; # only allow this for professors 1255 1256 print( CGI::hidden( 1257 -name => 'problemSeed', 1258 -value => $r->param("problemSeed") 1259 )) if defined($r->param("problemSeed")) and $permissionLevel>= $professorPermissionLevel; # only allow this for professors 1260 1261 1262 # end of main form 1263 print CGI::endform(); 1264 1265 print CGI::start_div({class=>"problemFooter"}); 1266 1267 1268 my $pastAnswersPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::ShowAnswers", 1269 courseID => $courseName); 1270 my $showPastAnswersURL = $self->systemLink($pastAnswersPage, authen => 0); # no authen info for form action 1271 1272 # print answer inspection button 1273 if ($authz->hasPermissions($user, "view_answers")) { 1274 print "\n", 1275 CGI::start_form(-method=>"POST",-action=>$showPastAnswersURL,-target=>"WW_Info"),"\n", 1276 $self->hidden_authen_fields,"\n", 1277 CGI::hidden(-name => 'courseID', -value=>$courseName), "\n", 1278 CGI::hidden(-name => 'problemID', -value=>$problem->problem_id), "\n", 1279 CGI::hidden(-name => 'setID', -value=>$problem->set_id), "\n", 1280 CGI::hidden(-name => 'studentUser', -value=>$problem->user_id), "\n", 1281 CGI::p( {-align=>"left"}, 1282 CGI::submit(-name => 'action', -value=>'Show Past Answers') 1283 ), "\n", 1284 CGI::endform(); 1285 } 1286 1287 1288 print $self->feedbackMacro( 1289 module => __PACKAGE__, 1290 set => $self->{set}->set_id, 1291 problem => $problem->problem_id, 1292 displayMode => $self->{displayMode}, 1293 showOldAnswers => $will{showOldAnswers}, 1294 showCorrectAnswers => $will{showCorrectAnswers}, 1295 showHints => $will{showHints}, 1296 showSolutions => $will{showSolutions}, 1297 pg_object => $pg, 1298 ); 1299 1300 print CGI::end_div(); 1301 1302 # debugging stuff 1303 if (0) { 1304 print 1305 CGI::hr(), 1306 CGI::h2("debugging information"), 1307 CGI::h3("form fields"), 1308 ref2string($self->{formFields}), 1309 CGI::h3("user object"), 1310 ref2string($self->{user}), 1311 CGI::h3("set object"), 1312 ref2string($set), 1313 CGI::h3("problem object"), 1314 ref2string($problem), 1315 CGI::h3("PG object"), 1316 ref2string($pg, {'WeBWorK::PG::Translator' => 1}); 1317 } 1318 debug("leaving body of Problem.pm"); 1319 return ""; 1320 } 1321 1322 1;
| aubreyja at gmail dot com | ViewVC Help |
| Powered by ViewVC 1.0.9 |