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