Parent Directory
|
Revision Log
Move options subroutine up to ContentGenerator.
Cleanup commented out code
Add facility for reading {status_message} to display messages when a call
is redirected from PGProblemEditor.pm
1 ################################################################################ 2 # WeBWorK Online Homework Delivery System 3 # Copyright © 2000-2003 The WeBWorK Project, http://openwebwork.sf.net/ 4 # $CVSHeader: webwork-modperl/lib/WeBWorK/ContentGenerator/Problem.pm,v 1.168 2004/11/18 16:00:37 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(); 29 use File::Path qw(rmtree); 30 use WeBWorK::Form; 31 use WeBWorK::PG; 32 use WeBWorK::PG::ImageGenerator; 33 use WeBWorK::PG::IO; 34 use WeBWorK::Utils qw(writeLog writeCourseLog encodeAnswers decodeAnswers ref2string makeTempDirectory); 35 use WeBWorK::DB::Utils qw(global2user user2global findDefaults); 36 use WeBWorK::Timing; 37 use URI::Escape; 38 39 use WeBWorK::Utils::Tasks qw(fake_set fake_problem); 40 41 ################################################################################ 42 # CGI param interface to this module (up-to-date as of v1.153) 43 ################################################################################ 44 45 # Standard params: 46 # 47 # user - user ID of real user 48 # key - session key 49 # effectiveUser - user ID of effective user 50 # 51 # Integration with PGProblemEditor: 52 # 53 # editMode - if set, indicates alternate problem source location. 54 # can be "temporaryFile" or "savedFile". 55 # 56 # sourceFilePath - path to file to be edited 57 # problemSeed - force problem seed to value 58 # success - success message to display 59 # failure - failure message to display 60 # 61 # Rendering options: 62 # 63 # displayMode - name of display mode to use 64 # 65 # showOldAnswers - request that last entered answer be shown (if allowed) 66 # showCorrectAnswers - request that correct answers be shown (if allowed) 67 # showHints - request that hints be shown (if allowed) 68 # showSolutions - request that solutions be shown (if allowed) 69 # 70 # Problem interaction: 71 # 72 # AnSwEr# - answer blanks in problem 73 # 74 # redisplay - name of the "Redisplay Problem" button 75 # submitAnswers - name of "Submit Answers" button 76 # checkAnswers - name of the "Check Answers" button 77 # previewAnswers - name of the "Preview Answers" button 78 79 ################################################################################ 80 # "can" methods 81 ################################################################################ 82 83 # Subroutines to determine if a user "can" perform an action. Each subroutine is 84 # called with the following arguments: 85 # 86 # ($self, $User, $EffectiveUser, $Set, $Problem) 87 88 sub can_showOldAnswers { 89 #my ($self, $User, $EffectiveUser, $Set, $Problem) = @_; 90 91 return 1; 92 } 93 94 sub can_showCorrectAnswers { 95 my ($self, $User, $EffectiveUser, $Set, $Problem) = @_; 96 my $authz = $self->r->authz; 97 98 return 99 after($Set->answer_date) 100 || 101 $authz->hasPermissions($User->user_id, "show_correct_answers_before_answer_date") 102 ; 103 } 104 105 sub can_showHints { 106 #my ($self, $User, $EffectiveUser, $Set, $Problem) = @_; 107 108 return 1; 109 } 110 111 sub can_showSolutions { 112 my ($self, $User, $EffectiveUser, $Set, $Problem) = @_; 113 my $authz = $self->r->authz; 114 115 return 116 after($Set->answer_date) 117 || 118 $authz->hasPermissions($User->user_id, "show_solutions_before_answer_date") 119 ; 120 } 121 122 sub can_recordAnswers { 123 my ($self, $User, $EffectiveUser, $Set, $Problem, $submitAnswers) = @_; 124 my $authz = $self->r->authz; 125 my $thisAttempt = $submitAnswers ? 1 : 0; 126 if ($User->user_id ne $EffectiveUser->user_id) { 127 return $authz->hasPermissions($User->user_id, "record_answers_when_acting_as_student"); 128 } 129 if (before($Set->open_date)) { 130 return $authz->hasPermissions($User->user_id, "record_answers_before_open_date"); 131 } elsif (between($Set->open_date, $Set->due_date)) { 132 my $max_attempts = $Problem->max_attempts; 133 my $attempts_used = $Problem->num_correct + $Problem->num_incorrect + $thisAttempt; 134 if ($max_attempts == -1 or $attempts_used < $max_attempts) { 135 return $authz->hasPermissions($User->user_id, "record_answers_after_open_date_with_attempts"); 136 } else { 137 return $authz->hasPermissions($User->user_id, "record_answers_after_open_date_without_attempts"); 138 } 139 } elsif (between($Set->due_date, $Set->answer_date)) { 140 return $authz->hasPermissions($User->user_id, "record_answers_after_due_date"); 141 } elsif (after($Set->answer_date)) { 142 return $authz->hasPermissions($User->user_id, "record_answers_after_answer_date"); 143 } 144 } 145 146 sub can_checkAnswers { 147 my ($self, $User, $EffectiveUser, $Set, $Problem, $submitAnswers) = @_; 148 my $authz = $self->r->authz; 149 my $thisAttempt = $submitAnswers ? 1 : 0; 150 151 if (before($Set->open_date)) { 152 return $authz->hasPermissions($User->user_id, "check_answers_before_open_date"); 153 } elsif (between($Set->open_date, $Set->due_date)) { 154 my $max_attempts = $Problem->max_attempts; 155 my $attempts_used = $Problem->num_correct + $Problem->num_incorrect + $thisAttempt; 156 if ($max_attempts == -1 or $attempts_used < $max_attempts) { 157 return $authz->hasPermissions($User->user_id, "check_answers_after_open_date_with_attempts"); 158 } else { 159 return $authz->hasPermissions($User->user_id, "check_answers_after_open_date_without_attempts"); 160 } 161 } elsif (between($Set->due_date, $Set->answer_date)) { 162 return $authz->hasPermissions($User->user_id, "check_answers_after_due_date"); 163 } elsif (after($Set->answer_date)) { 164 return $authz->hasPermissions($User->user_id, "check_answers_after_answer_date"); 165 } 166 } 167 168 # Helper functions for calculating times 169 sub before { return time <= $_[0] } 170 sub after { return time >= $_[0] } 171 sub between { my $t = time; return $t > $_[0] && $t < $_[1] } 172 173 ################################################################################ 174 # output utilities 175 ################################################################################ 176 177 sub attemptResults { 178 my $self = shift; 179 my $pg = shift; 180 my $showAttemptAnswers = shift; 181 my $showCorrectAnswers = shift; 182 my $showAttemptResults = $showAttemptAnswers && shift; 183 my $showSummary = shift; 184 my $showAttemptPreview = shift || 0; 185 186 my $ce = $self->r->ce; 187 188 my $problemResult = $pg->{result}; # the overall result of the problem 189 my @answerNames = @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} }; 190 191 my $showMessages = $showAttemptAnswers && grep { $pg->{answers}->{$_}->{ans_message} } @answerNames; 192 193 my $basename = "equation-" . $self->{set}->psvn. "." . $self->{problem}->problem_id . "-preview"; 194 195 # to make grabbing these options easier, we'll pull them out now... 196 my %imagesModeOptions = %{$ce->{pg}->{displayModeOptions}->{images}}; 197 198 my $imgGen = WeBWorK::PG::ImageGenerator->new( 199 tempDir => $ce->{webworkDirs}->{tmp}, 200 latex => $ce->{externalPrograms}->{latex}, 201 dvipng => $ce->{externalPrograms}->{dvipng}, 202 useCache => 1, 203 cacheDir => $ce->{webworkDirs}->{equationCache}, 204 cacheURL => $ce->{webworkURLs}->{equationCache}, 205 cacheDB => $ce->{webworkFiles}->{equationCacheDB}, 206 dvipng_align => $imagesModeOptions{dvipng_align}, 207 dvipng_depth_db => $imagesModeOptions{dvipng_depth_db}, 208 ); 209 210 my $header; 211 #$header .= CGI::th("Part"); 212 $header .= $showAttemptAnswers ? CGI::th("Entered") : ""; 213 $header .= $showAttemptPreview ? CGI::th("Answer Preview") : ""; 214 $header .= $showCorrectAnswers ? CGI::th("Correct") : ""; 215 $header .= $showAttemptResults ? CGI::th("Result") : ""; 216 $header .= $showMessages ? CGI::th("Messages") : ""; 217 my $fully = ''; 218 my @tableRows = ( $header ); 219 my $numCorrect = 0; 220 foreach my $name (@answerNames) { 221 my $answerResult = $pg->{answers}->{$name}; 222 my $studentAnswer = $answerResult->{student_ans}; # original_student_ans 223 my $preview = ($showAttemptPreview 224 ? $self->previewAnswer($answerResult, $imgGen) 225 : ""); 226 my $correctAnswer = $answerResult->{correct_ans}; 227 my $answerScore = $answerResult->{score}; 228 my $answerMessage = $showMessages ? $answerResult->{ans_message} : ""; 229 $answerMessage =~ s/\n/<BR>/g; 230 $numCorrect += $answerScore >= 1; 231 my $resultString = $answerScore >= 1 ? "correct" : 232 $answerScore > 0 ? int($answerScore*100)."% correct" : 233 "incorrect"; 234 $fully = 'completely ' if $answerScore >0 and $answerScore < 1; 235 236 # get rid of the goofy prefix on the answer names (supposedly, the format 237 # of the answer names is changeable. this only fixes it for "AnSwEr" 238 #$name =~ s/^AnSwEr//; 239 240 my $row; 241 #$row .= CGI::td($name); 242 $row .= $showAttemptAnswers ? CGI::td($self->nbsp($studentAnswer)) : ""; 243 $row .= $showAttemptPreview ? CGI::td($self->nbsp($preview)) : ""; 244 $row .= $showCorrectAnswers ? CGI::td($self->nbsp($correctAnswer)) : ""; 245 $row .= $showAttemptResults ? CGI::td($self->nbsp($resultString)) : ""; 246 $row .= $showMessages ? CGI::td({-class=>"Message"},$self->nbsp($answerMessage)) : ""; 247 push @tableRows, $row; 248 } 249 250 # render equation images 251 $imgGen->render(refresh => 1); 252 253 # my $numIncorrectNoun = scalar @answerNames == 1 ? "question" : "questions"; 254 my $scorePercent = sprintf("%.0f%%", $problemResult->{score} * 100); 255 # FIXME -- I left the old code in in case we have to back out. 256 # my $summary = "On this attempt, you answered $numCorrect out of " 257 # . scalar @answerNames . " $numIncorrectNoun correct, for a score of $scorePercent."; 258 my $summary = ""; 259 if (scalar @answerNames == 1) { 260 if ($numCorrect == scalar @answerNames) { 261 $summary .= CGI::div({class=>"ResultsWithoutError"},"The above answer is correct."); 262 } else { 263 $summary .= CGI::div({class=>"ResultsWithError"},"The above answer is NOT ${fully}correct."); 264 } 265 } else { 266 if ($numCorrect == scalar @answerNames) { 267 $summary .= CGI::div({class=>"ResultsWithoutError"},"All of the above answers are correct."); 268 } else { 269 $summary .= CGI::div({class=>"ResultsWithError"},"At least one of the above answers is NOT ${fully}correct."); 270 } 271 } 272 273 return 274 CGI::table({-class=>"attemptResults"}, CGI::Tr(\@tableRows)) 275 . ($showSummary ? CGI::p({class=>'emphasis'},$summary) : ""); 276 } 277 278 279 sub previewAnswer { 280 my ($self, $answerResult, $imgGen) = @_; 281 my $ce = $self->r->ce; 282 my $effectiveUser = $self->{effectiveUser}; 283 my $set = $self->{set}; 284 my $problem = $self->{problem}; 285 my $displayMode = $self->{displayMode}; 286 287 # note: right now, we have to do things completely differently when we are 288 # rendering math from INSIDE the translator and from OUTSIDE the translator. 289 # so we'll just deal with each case explicitly here. there's some code 290 # duplication that can be dealt with later by abstracting out tth/dvipng/etc. 291 292 my $tex = $answerResult->{preview_latex_string}; 293 294 return "" unless defined $tex and $tex ne ""; 295 296 if ($displayMode eq "plainText") { 297 return $tex; 298 } elsif ($displayMode eq "formattedText") { 299 my $tthCommand = $ce->{externalPrograms}->{tth} 300 . " -L -f5 -r 2> /dev/null <<END_OF_INPUT; echo > /dev/null\n" 301 . "\\(".$tex."\\)\n" 302 . "END_OF_INPUT\n"; 303 304 # call tth 305 my $result = `$tthCommand`; 306 if ($?) { 307 return "<b>[tth failed: $? $@]</b>"; 308 } else { 309 return $result; 310 } 311 } elsif ($displayMode eq "images") { 312 $imgGen->add($tex); 313 } elsif ($displayMode eq "jsMath") { 314 return '<DIV CLASS="math">'.$tex.'</DIV>' ; 315 } 316 } 317 318 ################################################################################ 319 # Template escape implementations 320 ################################################################################ 321 322 sub pre_header_initialize { 323 my ($self) = @_; 324 my $r = $self->r; 325 my $ce = $r->ce; 326 my $db = $r->db; 327 my $authz = $r->authz; 328 my $urlpath = $r->urlpath; 329 330 my $setName = $urlpath->arg("setID"); 331 my $problemNumber = $r->urlpath->arg("problemID"); 332 my $userName = $r->param('user'); 333 my $effectiveUserName = $r->param('effectiveUser'); 334 my $key = $r->param('key'); 335 336 my $user = $db->getUser($userName); # checked 337 die "record for user $userName (real user) does not exist." 338 unless defined $user; 339 340 my $effectiveUser = $db->getUser($effectiveUserName); # checked 341 die "record for user $effectiveUserName (effective user) does not exist." 342 unless defined $effectiveUser; 343 344 # obtain the merged set for $effectiveUser 345 my $set = $db->getMergedSet($effectiveUserName, $setName); # checked 346 347 # Database fix (in case of undefined published values) 348 # this is only necessary because some people keep holding to ww1.9 which did not have a published field 349 # make sure published is set to 0 or 1 350 if ( $set and $set->published ne "0" and $set->published ne "1") { 351 my $globalSet = $db->getGlobalSet($set->set_id); 352 $globalSet->published("1"); # defaults to published 353 $db->putGlobalSet($globalSet); 354 $set = $db->getMergedSet($effectiveUserName, $setName); 355 } else { 356 # don't do anything just yet, maybe we're a professor and we're 357 # fabricating a set or haven't assigned it to ourselves just yet 358 } 359 360 # obtain the merged problem for $effectiveUser 361 my $problem = $db->getMergedProblem($effectiveUserName, $setName, $problemNumber); # checked 362 363 my $editMode = $r->param("editMode"); 364 365 if ($authz->hasPermissions($userName, "modify_problem_sets")) { 366 # professors are allowed to fabricate sets and problems not 367 # assigned to them (or anyone). this allows them to use the 368 # editor to 369 370 # if a User Set does not exist for this user and this set 371 # then we check the Global Set 372 # if that does not exist we create a fake set 373 # if it does, we add fake user data 374 unless (defined $set) { 375 my $userSetClass = $db->{set_user}->{record}; 376 my $globalSet = $db->getGlobalSet($setName); # checked 377 378 if (not defined $globalSet) { 379 $set = fake_set($db); 380 } else { 381 $set = global2user($userSetClass, $globalSet); 382 $set->psvn(0); 383 } 384 } 385 386 # if that is not yet defined obtain the global problem, 387 # convert it to a user problem, and add fake user data 388 unless (defined $problem) { 389 my $userProblemClass = $db->{problem_user}->{record}; 390 my $globalProblem = $db->getGlobalProblem($setName, $problemNumber); # checked 391 # if the global problem doesn't exist either, bail! 392 if(not defined $globalProblem) { 393 my $sourceFilePath = $r->param("sourceFilePath"); 394 # These are problems from setmaker. If declared invalid, they won't come up 395 $self->{invalidProblem} = $self->{invalidSet} = 1 unless defined $sourceFilePath; 396 # die "Problem $problemNumber in set $setName does not exist" unless defined $sourceFilePath; 397 $problem = fake_problem($db); 398 $problem->problem_id(1); 399 $problem->source_file($sourceFilePath); 400 $problem->user_id($effectiveUserName); 401 } else { 402 $problem = global2user($userProblemClass, $globalProblem); 403 $problem->user_id($effectiveUserName); 404 $problem->problem_seed(0); 405 $problem->status(0); 406 $problem->attempted(0); 407 $problem->last_answer(""); 408 $problem->num_correct(0); 409 $problem->num_incorrect(0); 410 } 411 } 412 413 # now we're sure we have valid UserSet and UserProblem objects 414 # yay! 415 416 # now deal with possible editor overrides: 417 418 # if the caller is asking to override the source file, and 419 # editMode calls for a temporary file, do so 420 my $sourceFilePath = $r->param("sourceFilePath"); 421 if (defined $sourceFilePath and 422 (not defined $editMode or $editMode eq "temporaryFile")) { 423 $problem->source_file($sourceFilePath); 424 } 425 426 # if the problem does not have a source file or no source file has been passed in 427 # then this is really an invalid problem (probably from a bad URL) 428 $self->{invalidProblem} = not (defined $sourceFilePath or $problem->source_file); 429 430 # if the caller is asking to override the problem seed, do so 431 my $problemSeed = $r->param("problemSeed"); 432 if (defined $problemSeed) { 433 $problem->problem_seed($problemSeed); 434 } 435 436 my $publishedClass = ($set->published) ? "Published" : "Unpublished"; 437 my $publishedText = ($set->published) ? "visible to students." : "hidden from students."; 438 $self->addmessage(CGI::p("This set is " . CGI::font({class=>$publishedClass}, $publishedText))); 439 } else { 440 441 # A set is valid if it exists and if it is either published or the user is privileged. 442 $self->{invalidSet} = !(defined $set and ($set->published || $authz->hasPermissions($userName, "view_unpublished_sets"))); 443 $self->{invalidProblem} = !(defined $problem and ($set->published || $authz->hasPermissions($userName, "view_unpublished_sets"))); 444 445 $self->addbadmessage(CGI::p("This problem will not count towards your grade.")) if $problem and not $problem->value and not $self->{invalidProblem}; 446 } 447 448 $self->{userName} = $userName; 449 $self->{effectiveUserName} = $effectiveUserName; 450 $self->{user} = $user; 451 $self->{effectiveUser} = $effectiveUser; 452 $self->{set} = $set; 453 $self->{problem} = $problem; 454 $self->{editMode} = $editMode; 455 456 ##### form processing ##### 457 458 # set options from form fields (see comment at top of file for names) 459 my $displayMode = $r->param("displayMode") || $ce->{pg}->{options}->{displayMode}; 460 my $redisplay = $r->param("redisplay"); 461 my $submitAnswers = $r->param("submitAnswers"); 462 my $checkAnswers = $r->param("checkAnswers"); 463 my $previewAnswers = $r->param("previewAnswers"); 464 465 my $formFields = { WeBWorK::Form->new_from_paramable($r)->Vars }; 466 467 $self->{displayMode} = $displayMode; 468 $self->{redisplay} = $redisplay; 469 $self->{submitAnswers} = $submitAnswers; 470 $self->{checkAnswers} = $checkAnswers; 471 $self->{previewAnswers} = $previewAnswers; 472 $self->{formFields} = $formFields; 473 474 # get result and send to message 475 # my $success = $r->param("success"); 476 # my $failure = $r->param("failure"); 477 my $status_message = $r->param("status_message"); 478 # $self->addbadmessage(CGI::p($failure)) if $failure; 479 # $self->addgoodmessage(CGI::p($success)) if $success; 480 $self->addgoodmessage(CGI::p("$status_message")) if $status_message; 481 482 # now that we've set all the necessary variables quit out if the set or problem is invalid 483 return if $self->{invalidSet} || $self->{invalidProblem}; 484 485 ##### permissions ##### 486 487 # are we allowed to view this problem? 488 $self->{isOpen} = after($set->open_date) || $authz->hasPermissions($userName, "view_unopened_sets"); 489 return unless $self->{isOpen}; 490 491 # what does the user want to do? 492 #FIXME There is a problem with checkboxes -- if they are not checked they are invisible. Hence if the default mode in $ce is 1 493 # there is no way to override this. Probably this is ok for the last three options, but it was definitely not ok for showing 494 # saved answers which is normally on, but you want to be able to turn it off! This section should be moved to ContentGenerator 495 # so that you can set these options anywhere. We also need mechanisms for making them sticky. 496 my %want = ( 497 showOldAnswers => defined($r->param("showOldAnswers")) ? $r->param("showOldAnswers") : $ce->{pg}->{options}->{showOldAnswers}, 498 showCorrectAnswers => $r->param("showCorrectAnswers") || $ce->{pg}->{options}->{showCorrectAnswers}, 499 showHints => $r->param("showHints") || $ce->{pg}->{options}->{showHints}, 500 showSolutions => $r->param("showSolutions") || $ce->{pg}->{options}->{showSolutions}, 501 recordAnswers => $submitAnswers, 502 checkAnswers => $checkAnswers, 503 getSubmitButton => 1, 504 ); 505 506 # are certain options enforced? 507 my %must = ( 508 showOldAnswers => 0, 509 showCorrectAnswers => 0, 510 showHints => 0, 511 showSolutions => 0, 512 recordAnswers => ! $authz->hasPermissions($userName, "avoid_recording_answers"), 513 checkAnswers => 0, 514 getSubmitButton => 0, 515 ); 516 517 # does the user have permission to use certain options? 518 my @args = ($user, $effectiveUser, $set, $problem); 519 my %can = ( 520 showOldAnswers => $self->can_showOldAnswers(@args), 521 showCorrectAnswers => $self->can_showCorrectAnswers(@args), 522 showHints => $self->can_showHints(@args), 523 showSolutions => $self->can_showSolutions(@args), 524 recordAnswers => $self->can_recordAnswers(@args, 0), 525 checkAnswers => $self->can_checkAnswers(@args, $submitAnswers), 526 getSubmitButton => $self->can_recordAnswers(@args, $submitAnswers), 527 ); 528 529 # final values for options 530 my %will; 531 foreach (keys %must) { 532 $will{$_} = $can{$_} && ($want{$_} || $must{$_}); 533 } 534 535 ##### sticky answers ##### 536 537 if (not ($submitAnswers or $previewAnswers or $checkAnswers) and $will{showOldAnswers}) { 538 # do this only if new answers are NOT being submitted 539 my %oldAnswers = decodeAnswers($problem->last_answer); 540 $formFields->{$_} = $oldAnswers{$_} foreach keys %oldAnswers; 541 } 542 543 ##### translation ##### 544 545 $WeBWorK::timer->continue("begin pg processing") if defined($WeBWorK::timer); 546 my $pg = WeBWorK::PG->new( 547 $ce, 548 $effectiveUser, 549 $key, 550 $set, 551 $problem, 552 $set->psvn, # FIXME: this field should be removed 553 $formFields, 554 { # translation options 555 displayMode => $displayMode, 556 showHints => $will{showHints}, 557 showSolutions => $will{showSolutions}, 558 refreshMath2img => $will{showHints} || $will{showSolutions}, 559 processAnswers => 1, 560 }, 561 ); 562 563 $WeBWorK::timer->continue("end pg processing") if defined($WeBWorK::timer); 564 565 ##### fix hint/solution options ##### 566 567 $can{showHints} &&= $pg->{flags}->{hintExists} 568 &&= $pg->{flags}->{showHintLimit}<=$pg->{state}->{num_of_incorrect_ans}; 569 $can{showSolutions} &&= $pg->{flags}->{solutionExists}; 570 571 ##### store fields ##### 572 573 $self->{want} = \%want; 574 $self->{must} = \%must; 575 $self->{can} = \%can; 576 $self->{will} = \%will; 577 $self->{pg} = $pg; 578 } 579 580 sub if_errors($$) { 581 my ($self, $arg) = @_; 582 583 if ($self->{isOpen}) { 584 return $self->{pg}->{flags}->{error_flag} ? $arg : !$arg; 585 } else { 586 return !$arg; 587 } 588 } 589 590 sub head { 591 my ($self) = @_; 592 593 return "" unless $self->{isOpen}; 594 return $self->{pg}->{head_text} if $self->{pg}->{head_text}; 595 } 596 597 # sub options { 598 # my ($self) = @_; 599 # warn "doing options in Problem"; 600 # return "" if $self->{invalidProblem}; 601 # my $sourceFilePathfield = ''; 602 # if($self->r->param("sourceFilePath")) { 603 # $sourceFilePathfield = CGI::hidden(-name => "sourceFilePath", 604 # -value => $self->r->param("sourceFilePath")); 605 # } 606 # 607 # return join("", 608 # CGI::start_form("POST", $self->{r}->uri), 609 # $self->hidden_authen_fields, 610 # $sourceFilePathfield, 611 # CGI::hr(), 612 # CGI::start_div({class=>"viewOptions"}), 613 # $self->viewOptions(), 614 # CGI::end_div(), 615 # CGI::end_form() 616 # ); 617 # } 618 619 sub siblings { 620 my ($self) = @_; 621 my $r = $self->r; 622 my $db = $r->db; 623 my $urlpath = $r->urlpath; 624 625 # can't show sibling problems if the set is invalid 626 return "" if $self->{invalidSet}; 627 628 my $courseID = $urlpath->arg("courseID"); 629 my $setID = $self->{set}->set_id; 630 my $eUserID = $r->param("effectiveUser"); 631 my @problemIDs = sort { $a <=> $b } $db->listUserProblems($eUserID, $setID); 632 633 print CGI::start_ul({class=>"LinksMenu"}); 634 print CGI::start_li(); 635 print CGI::span({style=>"font-size:larger"}, "Problems"); 636 print CGI::start_ul(); 637 638 foreach my $problemID (@problemIDs) { 639 my $problemPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Problem", 640 courseID => $courseID, setID => $setID, problemID => $problemID); 641 print CGI::li(CGI::a( {href=>$self->systemLink($problemPage, 642 params=>{ displayMode => $self->{displayMode}, 643 showOldAnswers => $self->{will}->{showOldAnswers} 644 })}, "Problem $problemID") 645 ); 646 } 647 648 print CGI::end_ul(); 649 print CGI::end_li(); 650 print CGI::end_ul(); 651 652 return ""; 653 } 654 655 sub nav { 656 my ($self, $args) = @_; 657 my $r = $self->r; 658 my $db = $r->db; 659 my $urlpath = $r->urlpath; 660 661 my $courseID = $urlpath->arg("courseID"); 662 my $setID = $self->{set}->set_id if !($self->{invalidSet}); 663 my $problemID = $self->{problem}->problem_id if !($self->{invalidProblem}); 664 my $eUserID = $r->param("effectiveUser"); 665 666 my ($prevID, $nextID); 667 668 if (!$self->{invalidProblem}) { 669 my @problemIDs = $db->listUserProblems($eUserID, $setID); 670 foreach my $id (@problemIDs) { 671 $prevID = $id if $id < $problemID 672 and (not defined $prevID or $id > $prevID); 673 $nextID = $id if $id > $problemID 674 and (not defined $nextID or $id < $nextID); 675 } 676 } 677 678 my @links; 679 680 if ($prevID) { 681 my $prevPage = $urlpath->newFromModule(__PACKAGE__, 682 courseID => $courseID, setID => $setID, problemID => $prevID); 683 push @links, "Previous Problem", $r->location . $prevPage->path, "navPrev"; 684 } else { 685 push @links, "Previous Problem", "", "navPrev"; 686 } 687 688 push @links, "Problem List", $r->location . $urlpath->parent->path, "navProbList"; 689 690 if ($nextID) { 691 my $nextPage = $urlpath->newFromModule(__PACKAGE__, 692 courseID => $courseID, setID => $setID, problemID => $nextID); 693 push @links, "Next Problem", $r->location . $nextPage->path, "navNext"; 694 } else { 695 push @links, "Next Problem", "", "navNext"; 696 } 697 698 my $tail = "&displayMode=".$self->{displayMode}."&showOldAnswers=".$self->{will}->{showOldAnswers}; 699 return $self->navMacro($args, $tail, @links); 700 } 701 702 sub title { 703 my ($self) = @_; 704 705 # using the url arguments won't break if the set/problem are invalid 706 my $setID = $self->r->urlpath->arg("setID"); 707 my $problemID = $self->r->urlpath->arg("problemID"); 708 709 return "$setID: Problem $problemID"; 710 } 711 712 sub body { 713 my $self = shift; 714 my $r = $self->r; 715 my $ce = $r->ce; 716 my $db = $r->db; 717 my $authz = $r->authz; 718 my $urlpath = $r->urlpath; 719 my $user = $r->param('user'); 720 my $effectiveUser = $r->param('effectiveUser'); 721 722 if ($self->{invalidSet}) { 723 return CGI::div({class=>"ResultsWithError"}, 724 CGI::p("The selected problem set (" . $urlpath->arg("setID") . ") is not a valid set for " . $r->param("effectiveUser") . ".")); 725 } 726 727 if ($self->{invalidProblem}) { 728 return CGI::div({class=>"ResultsWithError"}, 729 CGI::p("The selected problem (" . $urlpath->arg("problemID") . ") is not a valid problem for set " . $self->{set}->set_id . ".")); 730 } 731 732 unless ($self->{isOpen}) { 733 return CGI::div({class=>"ResultsWithError"}, 734 CGI::p("This problem is not available because the problem set that contains it is not yet open.")); 735 } 736 # unpack some useful variables 737 my $set = $self->{set}; 738 my $problem = $self->{problem}; 739 my $editMode = $self->{editMode}; 740 my $submitAnswers = $self->{submitAnswers}; 741 my $checkAnswers = $self->{checkAnswers}; 742 my $previewAnswers = $self->{previewAnswers}; 743 my %want = %{ $self->{want} }; 744 my %can = %{ $self->{can} }; 745 my %must = %{ $self->{must} }; 746 my %will = %{ $self->{will} }; 747 my $pg = $self->{pg}; 748 749 my $courseName = $urlpath->arg("courseID"); 750 751 # FIXME: move editor link to top, next to problem number. 752 # format as "[edit]" like we're doing with course info file, etc. 753 # add edit link for set as well. 754 my $editorLink = ""; 755 # if we are here without a real problem set, carry that through 756 my $forced_field = []; 757 $forced_field = ['sourceFilePath' => $r->param("sourceFilePath")] if 758 ($set->set_id eq 'Undefined_Set'); 759 if ($authz->hasPermissions($user, "modify_problem_sets")) { 760 my $editorPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::PGProblemEditor", 761 courseID => $courseName, setID => $set->set_id, problemID => $problem->problem_id); 762 my $editorURL = $self->systemLink($editorPage, params=>$forced_field); 763 $editorLink = CGI::a({href=>$editorURL}, "Edit this problem"); 764 } 765 766 ##### translation errors? ##### 767 768 if ($pg->{flags}->{error_flag}) { 769 print $self->errorOutput($pg->{errors}, $pg->{body_text}); 770 print $editorLink; 771 return ""; 772 } 773 774 ##### answer processing ##### 775 $WeBWorK::timer->continue("begin answer processing") if defined($WeBWorK::timer); 776 # if answers were submitted: 777 my $scoreRecordedMessage; 778 my $pureProblem; 779 if ($submitAnswers) { 780 # get a "pure" (unmerged) UserProblem to modify 781 # this will be undefined if the problem has not been assigned to this user 782 $pureProblem = $db->getUserProblem($problem->user_id, $problem->set_id, $problem->problem_id); # checked 783 if (defined $pureProblem) { 784 # store answers in DB for sticky answers 785 my %answersToStore; 786 my %answerHash = %{ $pg->{answers} }; 787 $answersToStore{$_} = $self->{formFields}->{$_} #$answerHash{$_}->{original_student_ans} -- this may have been modified for fields with multiple values. Don't use it!! 788 foreach (keys %answerHash); 789 790 # There may be some more answers to store -- one which are auxiliary entries to a primary answer. Evaluating 791 # matrices works in this way, only the first answer triggers an answer evaluator, the rest are just inputs 792 # however we need to store them. Fortunately they are still in the input form. 793 my @extra_answer_names = @{ $pg->{flags}->{KEPT_EXTRA_ANSWERS}}; 794 $answersToStore{$_} = $self->{formFields}->{$_} foreach (@extra_answer_names); 795 796 # Now let's encode these answers to store them -- append the extra answers to the end of answer entry order 797 my @answer_order = (@{$pg->{flags}->{ANSWER_ENTRY_ORDER}}, @extra_answer_names); 798 my $answerString = encodeAnswers(%answersToStore, 799 @answer_order); 800 801 # store last answer to database 802 $problem->last_answer($answerString); 803 $pureProblem->last_answer($answerString); 804 $db->putUserProblem($pureProblem); 805 806 # store state in DB if it makes sense 807 if ($will{recordAnswers}) { 808 $problem->status($pg->{state}->{recorded_score}); 809 $problem->attempted(1); 810 $problem->num_correct($pg->{state}->{num_of_correct_ans}); 811 $problem->num_incorrect($pg->{state}->{num_of_incorrect_ans}); 812 $pureProblem->status($pg->{state}->{recorded_score}); 813 $pureProblem->attempted(1); 814 $pureProblem->num_correct($pg->{state}->{num_of_correct_ans}); 815 $pureProblem->num_incorrect($pg->{state}->{num_of_incorrect_ans}); 816 if ($db->putUserProblem($pureProblem)) { 817 $scoreRecordedMessage = "Your score was recorded."; 818 } else { 819 $scoreRecordedMessage = "Your score was not recorded because there was a failure in storing the problem record to the database."; 820 } 821 # write to the transaction log, just to make sure 822 writeLog($self->{ce}, "transaction", 823 $problem->problem_id."\t". 824 $problem->set_id."\t". 825 $problem->user_id."\t". 826 $problem->source_file."\t". 827 $problem->value."\t". 828 $problem->max_attempts."\t". 829 $problem->problem_seed."\t". 830 $pureProblem->status."\t". 831 $pureProblem->attempted."\t". 832 $pureProblem->last_answer."\t". 833 $pureProblem->num_correct."\t". 834 $pureProblem->num_incorrect 835 ); 836 } else { 837 if (before($set->open_date) or after($set->due_date)) { 838 $scoreRecordedMessage = "Your score was not recorded because this problem set is closed."; 839 } else { 840 $scoreRecordedMessage = "Your score was not recorded."; 841 } 842 } 843 } else { 844 $scoreRecordedMessage = "Your score was not recorded because this problem has not been assigned to you."; 845 } 846 } 847 848 # logging student answers 849 850 my $answer_log = $self->{ce}->{courseFiles}->{logs}->{'answer_log'}; 851 if ( defined($answer_log ) and defined($pureProblem)) { 852 if ($submitAnswers && !$authz->hasPermissions($effectiveUser, "dont_log_past_answers")) { 853 my $answerString = ""; my $scores = ""; 854 my %answerHash = %{ $pg->{answers} }; 855 # FIXME this is the line 552 error. make sure original student ans is defined. 856 # The fact that it is not defined is probably due to an error in some answer evaluator. 857 # But I think it is useful to suppress this error message in the log. 858 foreach (sort keys %answerHash) { 859 my $orig_ans = $answerHash{$_}->{original_student_ans}; 860 my $student_ans = defined $orig_ans ? $orig_ans : ''; 861 $answerString .= $student_ans."\t"; 862 $scores .= $answerHash{$_}->{score} >= 1 ? "1" : "0"; 863 } 864 $answerString = '' unless defined($answerString); # insure string is defined. 865 writeCourseLog($self->{ce}, "answer_log", 866 join("", 867 '|', $problem->user_id, 868 '|', $problem->set_id, 869 '|', $problem->problem_id, 870 '|', $scores, "\t", 871 time(),"\t", 872 $answerString, 873 ), 874 ); 875 876 } 877 } 878 879 $WeBWorK::timer->continue("end answer processing") if defined($WeBWorK::timer); 880 881 ##### output ##### 882 # custom message for editor 883 if ($authz->hasPermissions($user, "modify_problem_sets") and defined $editMode) { 884 if ($editMode eq "temporaryFile") { 885 print CGI::p(CGI::div({class=>'temporaryFile'}, "Viewing temporary file: ", $problem->source_file)); 886 } elsif ($editMode eq "savedFile") { 887 # taken care of in the initialization phase 888 } 889 } 890 print CGI::start_div({class=>"problemHeader"}); 891 892 893 894 # attempt summary 895 #FIXME -- the following is a kludge: if showPartialCorrectAnswers is negative don't show anything. 896 # until after the due date 897 # do I need to check $will{showCorrectAnswers} to make preflight work?? 898 if (($pg->{flags}->{showPartialCorrectAnswers} >= 0 and $submitAnswers) ) { 899 # print this if user submitted answers OR requested correct answers 900 901 print $self->attemptResults($pg, 1, 902 $will{showCorrectAnswers}, 903 $pg->{flags}->{showPartialCorrectAnswers}, 1, 1); 904 } elsif ($checkAnswers) { 905 # print this if user previewed answers 906 print CGI::div({class=>'ResultsWithError'},"ANSWERS ONLY CHECKED -- ANSWERS NOT RECORDED"), CGI::br(); 907 print $self->attemptResults($pg, 1, $will{showCorrectAnswers}, 1, 1, 1); 908 # show attempt answers 909 # show correct answers if asked 910 # show attempt results (correctness) 911 # show attempt previews 912 } elsif ($previewAnswers) { 913 # print this if user previewed answers 914 print CGI::div({class=>'ResultsWithError'},"PREVIEW ONLY -- ANSWERS NOT RECORDED"),CGI::br(),$self->attemptResults($pg, 1, 0, 0, 0, 1); 915 # show attempt answers 916 # don't show correct answers 917 # don't show attempt results (correctness) 918 # show attempt previews 919 } 920 921 print CGI::end_div(); 922 923 # main form 924 print CGI::startform("POST", $r->uri); 925 print $self->hidden_authen_fields; 926 927 print CGI::start_div({class=>"problem"}); 928 print CGI::p($pg->{body_text}); 929 print CGI::p(CGI::b("Note: "), CGI::i($pg->{result}->{msg})) if $pg->{result}->{msg}; 930 print CGI::end_div(); 931 932 print CGI::start_p(); 933 934 if ($can{showCorrectAnswers}) { 935 print CGI::checkbox( 936 -name => "showCorrectAnswers", 937 -checked => $will{showCorrectAnswers}, 938 -label => "Show correct answers", 939 ); 940 } 941 if ($can{showHints}) { 942 print CGI::div({style=>"color:red"}, 943 CGI::checkbox( 944 -name => "showHints", 945 -checked => $will{showHints}, 946 -label => "Show Hints", 947 ) 948 ); 949 } 950 if ($can{showSolutions}) { 951 print CGI::checkbox( 952 -name => "showSolutions", 953 -checked => $will{showSolutions}, 954 -label => "Show Solutions", 955 ); 956 } 957 958 if ($can{showCorrectAnswers} or $can{showHints} or $can{showSolutions}) { 959 print CGI::br(); 960 } 961 962 print CGI::submit(-name=>"previewAnswers", -label=>"Preview Answers"); 963 if ($can{checkAnswers}) { 964 print CGI::submit(-name=>"checkAnswers", -label=>"Check Answers"); 965 } 966 if ($can{getSubmitButton}) { 967 if ($user ne $effectiveUser) { 968 # if acting as a student, make it clear that answer submissions will 969 # apply to the student's records, not the professor's. 970 print CGI::submit(-name=>"submitAnswers", -label=>"Submit Answers for $effectiveUser"); 971 } else { 972 print CGI::submit(-name=>"submitAnswers", -label=>"Submit Answers"); 973 } 974 } 975 976 print CGI::end_p(); 977 978 print CGI::start_div({class=>"scoreSummary"}); 979 980 # score summary 981 my $attempts = $problem->num_correct + $problem->num_incorrect; 982 my $attemptsNoun = $attempts != 1 ? "times" : "time"; 983 my $problem_status = $problem->status || 0; 984 my $lastScore = sprintf("%.0f%%", $problem_status * 100); # Round to whole number 985 my ($attemptsLeft, $attemptsLeftNoun); 986 if ($problem->max_attempts == -1) { 987 # unlimited attempts 988 $attemptsLeft = "unlimited"; 989 $attemptsLeftNoun = "attempts"; 990 } else { 991 $attemptsLeft = $problem->max_attempts - $attempts; 992 $attemptsLeftNoun = $attemptsLeft == 1 ? "attempt" : "attempts"; 993 } 994 995 my $setClosed = 0; 996 my $setClosedMessage; 997 if (before($set->open_date) or after($set->due_date)) { 998 $setClosed = 1; 999 $setClosedMessage = "This problem set is closed."; 1000 if ($authz->hasPermissions($user, "view_answers")) { 1001 $setClosedMessage .= " However, since you are a privileged user, additional attempts will be recorded."; 1002 } else { 1003 $setClosedMessage .= " Additional attempts will not be recorded."; 1004 } 1005 } 1006 1007 my $notCountedMessage = ($problem->value) ? "" : "(This problem will not count towards your grade.)"; 1008 print CGI::p( 1009 $submitAnswers ? $scoreRecordedMessage . CGI::br() : "", 1010 "You have attempted this problem $attempts $attemptsNoun.", CGI::br(), 1011 $problem->attempted 1012 ? "Your recorded score is $lastScore. $notCountedMessage" . CGI::br() 1013 : "", 1014 $setClosed ? $setClosedMessage : "You have $attemptsLeft $attemptsLeftNoun remaining." 1015 ); 1016 print CGI::end_div(); 1017 1018 # save state for viewOptions 1019 print CGI::hidden( 1020 -name => "showOldAnswers", 1021 -value => $will{showOldAnswers} 1022 ), 1023 1024 CGI::hidden( 1025 -name => "displayMode", 1026 -value => $self->{displayMode} 1027 ); 1028 print( CGI::hidden( 1029 -name => 'editMode', 1030 -value => $self->{editMode}, 1031 ) 1032 ) if defined($self->{editMode}) and $self->{editMode} eq 'temporaryFile'; 1033 print( CGI::hidden( 1034 -name => 'sourceFilePath', 1035 -value => $self->{problem}->{source_file} 1036 )) if defined($self->{problem}->{source_file}); 1037 1038 print( CGI::hidden( 1039 -name => 'problemSeed', 1040 -value => $r->param("problemSeed") 1041 )) if defined($r->param("problemSeed")); 1042 1043 # end of main form 1044 print CGI::endform(); 1045 1046 print CGI::start_div({class=>"problemFooter"}); 1047 1048 ## arguments for answer inspection button 1049 #my $prof_url = $ce->{webworkURLs}->{oldProf}; 1050 #my $webworkURL = $ce->{webworkURLs}->{root}; 1051 #my $cgi_url = $prof_url; 1052 #$cgi_url=~ s|/[^/]*$||; # clip profLogin.pl 1053 #my $authen_args = $self->url_authen_args(); 1054 #my $showPastAnswersURL = "$webworkURL/$courseName/instructor/show_answers/"; 1055 1056 my $pastAnswersPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::ShowAnswers", 1057 courseID => $courseName); 1058 my $showPastAnswersURL = $self->systemLink($pastAnswersPage, authen => 0); # no authen info for form action 1059 1060 # print answer inspection button 1061 if ($authz->hasPermissions($user, "view_answers")) { 1062 print "\n", 1063 CGI::start_form(-method=>"POST",-action=>$showPastAnswersURL,-target=>"information"),"\n", 1064 $self->hidden_authen_fields,"\n", 1065 CGI::hidden(-name => 'courseID', -value=>$courseName), "\n", 1066 CGI::hidden(-name => 'problemID', -value=>$problem->problem_id), "\n", 1067 CGI::hidden(-name => 'setID', -value=>$problem->set_id), "\n", 1068 CGI::hidden(-name => 'studentUser', -value=>$problem->user_id), "\n", 1069 CGI::p( {-align=>"left"}, 1070 CGI::submit(-name => 'action', -value=>'Show Past Answers') 1071 ), "\n", 1072 CGI::endform(); 1073 } 1074 1075 # feedback form url 1076 my $feedbackPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Feedback", 1077 courseID => $courseName); 1078 my $feedbackURL = $self->systemLink($feedbackPage, authen => 0); # no authen info for form action 1079 1080 #print feedback form 1081 print 1082 CGI::start_form(-method=>"POST", -action=>$feedbackURL),"\n", 1083 $self->hidden_authen_fields,"\n", 1084 CGI::hidden("module", __PACKAGE__),"\n", 1085 CGI::hidden("set", $set->set_id),"\n", 1086 CGI::hidden("problem", $problem->problem_id),"\n", 1087 CGI::hidden("displayMode", $self->{displayMode}),"\n", 1088 CGI::hidden("showOldAnswers", $will{showOldAnswers}),"\n", 1089 CGI::hidden("showCorrectAnswers", $will{showCorrectAnswers}),"\n", 1090 CGI::hidden("showHints", $will{showHints}),"\n", 1091 CGI::hidden("showSolutions", $will{showSolutions}),"\n", 1092 CGI::p({-align=>"left"}, 1093 CGI::submit(-name=>"feedbackForm", -label=>"Email instructor") 1094 ), 1095 CGI::endform(),"\n"; 1096 1097 # FIXME print editor link 1098 print $editorLink; #empty unless it is appropriate to have an editor link. 1099 1100 print CGI::end_div(); 1101 1102 # debugging stuff 1103 if (0) { 1104 print 1105 CGI::hr(), 1106 CGI::h2("debugging information"), 1107 CGI::h3("form fields"), 1108 ref2string($self->{formFields}), 1109 CGI::h3("user object"), 1110 ref2string($self->{user}), 1111 CGI::h3("set object"), 1112 ref2string($set), 1113 CGI::h3("problem object"), 1114 ref2string($problem), 1115 CGI::h3("PG object"), 1116 ref2string($pg, {'WeBWorK::PG::Translator' => 1}); 1117 } 1118 1119 return ""; 1120 } 1121 1122 1;
| aubreyja at gmail dot com | ViewVC Help |
| Powered by ViewVC 1.0.9 |