Parent Directory
|
Revision Log
Better spacing of jsMath output in the answer preview area.
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.171 2005/06/28 00:16:08 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(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 '<SPAN CLASS="math">\\displaystyle{'.$tex.'}</SPAN>'; 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 $status_message = $r->param("status_message"); 476 $self->addmessage(CGI::p("$status_message")) if $status_message; 477 478 # now that we've set all the necessary variables quit out if the set or problem is invalid 479 return if $self->{invalidSet} || $self->{invalidProblem}; 480 481 ##### permissions ##### 482 483 # are we allowed to view this problem? 484 $self->{isOpen} = after($set->open_date) || $authz->hasPermissions($userName, "view_unopened_sets"); 485 return unless $self->{isOpen}; 486 487 # what does the user want to do? 488 #FIXME There is a problem with checkboxes -- if they are not checked they are invisible. Hence if the default mode in $ce is 1 489 # there is no way to override this. Probably this is ok for the last three options, but it was definitely not ok for showing 490 # saved answers which is normally on, but you want to be able to turn it off! This section should be moved to ContentGenerator 491 # so that you can set these options anywhere. We also need mechanisms for making them sticky. 492 my %want = ( 493 showOldAnswers => defined($r->param("showOldAnswers")) ? $r->param("showOldAnswers") : $ce->{pg}->{options}->{showOldAnswers}, 494 showCorrectAnswers => $r->param("showCorrectAnswers") || $ce->{pg}->{options}->{showCorrectAnswers}, 495 showHints => $r->param("showHints") || $ce->{pg}->{options}->{showHints}, 496 showSolutions => $r->param("showSolutions") || $ce->{pg}->{options}->{showSolutions}, 497 recordAnswers => $submitAnswers, 498 checkAnswers => $checkAnswers, 499 getSubmitButton => 1, 500 ); 501 502 # are certain options enforced? 503 my %must = ( 504 showOldAnswers => 0, 505 showCorrectAnswers => 0, 506 showHints => 0, 507 showSolutions => 0, 508 recordAnswers => ! $authz->hasPermissions($userName, "avoid_recording_answers"), 509 checkAnswers => 0, 510 getSubmitButton => 0, 511 ); 512 513 # does the user have permission to use certain options? 514 my @args = ($user, $effectiveUser, $set, $problem); 515 my %can = ( 516 showOldAnswers => $self->can_showOldAnswers(@args), 517 showCorrectAnswers => $self->can_showCorrectAnswers(@args), 518 showHints => $self->can_showHints(@args), 519 showSolutions => $self->can_showSolutions(@args), 520 recordAnswers => $self->can_recordAnswers(@args, 0), 521 checkAnswers => $self->can_checkAnswers(@args, $submitAnswers), 522 getSubmitButton => $self->can_recordAnswers(@args, $submitAnswers), 523 ); 524 525 # final values for options 526 my %will; 527 foreach (keys %must) { 528 $will{$_} = $can{$_} && ($want{$_} || $must{$_}); 529 } 530 531 ##### sticky answers ##### 532 533 if (not ($submitAnswers or $previewAnswers or $checkAnswers) and $will{showOldAnswers}) { 534 # do this only if new answers are NOT being submitted 535 my %oldAnswers = decodeAnswers($problem->last_answer); 536 $formFields->{$_} = $oldAnswers{$_} foreach keys %oldAnswers; 537 } 538 539 ##### translation ##### 540 541 $WeBWorK::timer->continue("begin pg processing") if defined($WeBWorK::timer); 542 my $pg = WeBWorK::PG->new( 543 $ce, 544 $effectiveUser, 545 $key, 546 $set, 547 $problem, 548 $set->psvn, # FIXME: this field should be removed 549 $formFields, 550 { # translation options 551 displayMode => $displayMode, 552 showHints => $will{showHints}, 553 showSolutions => $will{showSolutions}, 554 refreshMath2img => $will{showHints} || $will{showSolutions}, 555 processAnswers => 1, 556 }, 557 ); 558 559 $WeBWorK::timer->continue("end pg processing") if defined($WeBWorK::timer); 560 561 ##### fix hint/solution options ##### 562 563 $can{showHints} &&= $pg->{flags}->{hintExists} 564 &&= $pg->{flags}->{showHintLimit}<=$pg->{state}->{num_of_incorrect_ans}; 565 $can{showSolutions} &&= $pg->{flags}->{solutionExists}; 566 567 ##### store fields ##### 568 569 $self->{want} = \%want; 570 $self->{must} = \%must; 571 $self->{can} = \%can; 572 $self->{will} = \%will; 573 $self->{pg} = $pg; 574 } 575 576 sub if_errors($$) { 577 my ($self, $arg) = @_; 578 579 if ($self->{isOpen}) { 580 return $self->{pg}->{flags}->{error_flag} ? $arg : !$arg; 581 } else { 582 return !$arg; 583 } 584 } 585 586 sub head { 587 my ($self) = @_; 588 589 return "" unless $self->{isOpen}; 590 return $self->{pg}->{head_text} if $self->{pg}->{head_text}; 591 } 592 593 # sub options { 594 # my ($self) = @_; 595 # warn "doing options in Problem"; 596 # return "" if $self->{invalidProblem}; 597 # my $sourceFilePathfield = ''; 598 # if($self->r->param("sourceFilePath")) { 599 # $sourceFilePathfield = CGI::hidden(-name => "sourceFilePath", 600 # -value => $self->r->param("sourceFilePath")); 601 # } 602 # 603 # return join("", 604 # CGI::start_form("POST", $self->{r}->uri), 605 # $self->hidden_authen_fields, 606 # $sourceFilePathfield, 607 # CGI::hr(), 608 # CGI::start_div({class=>"viewOptions"}), 609 # $self->viewOptions(), 610 # CGI::end_div(), 611 # CGI::end_form() 612 # ); 613 # } 614 615 sub siblings { 616 my ($self) = @_; 617 my $r = $self->r; 618 my $db = $r->db; 619 my $urlpath = $r->urlpath; 620 621 # can't show sibling problems if the set is invalid 622 return "" if $self->{invalidSet}; 623 624 my $courseID = $urlpath->arg("courseID"); 625 my $setID = $self->{set}->set_id; 626 my $eUserID = $r->param("effectiveUser"); 627 my @problemIDs = sort { $a <=> $b } $db->listUserProblems($eUserID, $setID); 628 629 print CGI::start_ul({class=>"LinksMenu"}); 630 print CGI::start_li(); 631 print CGI::span({style=>"font-size:larger"}, "Problems"); 632 print CGI::start_ul(); 633 634 foreach my $problemID (@problemIDs) { 635 my $problemPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Problem", 636 courseID => $courseID, setID => $setID, problemID => $problemID); 637 print CGI::li(CGI::a( {href=>$self->systemLink($problemPage, 638 params=>{ displayMode => $self->{displayMode}, 639 showOldAnswers => $self->{will}->{showOldAnswers} 640 })}, "Problem $problemID") 641 ); 642 } 643 644 print CGI::end_ul(); 645 print CGI::end_li(); 646 print CGI::end_ul(); 647 648 return ""; 649 } 650 651 sub nav { 652 my ($self, $args) = @_; 653 my $r = $self->r; 654 my $db = $r->db; 655 my $urlpath = $r->urlpath; 656 657 my $courseID = $urlpath->arg("courseID"); 658 my $setID = $self->{set}->set_id if !($self->{invalidSet}); 659 my $problemID = $self->{problem}->problem_id if !($self->{invalidProblem}); 660 my $eUserID = $r->param("effectiveUser"); 661 662 my ($prevID, $nextID); 663 664 if (!$self->{invalidProblem}) { 665 my @problemIDs = $db->listUserProblems($eUserID, $setID); 666 foreach my $id (@problemIDs) { 667 $prevID = $id if $id < $problemID 668 and (not defined $prevID or $id > $prevID); 669 $nextID = $id if $id > $problemID 670 and (not defined $nextID or $id < $nextID); 671 } 672 } 673 674 my @links; 675 676 if ($prevID) { 677 my $prevPage = $urlpath->newFromModule(__PACKAGE__, 678 courseID => $courseID, setID => $setID, problemID => $prevID); 679 push @links, "Previous Problem", $r->location . $prevPage->path, "navPrev"; 680 } else { 681 push @links, "Previous Problem", "", "navPrev"; 682 } 683 684 push @links, "Problem List", $r->location . $urlpath->parent->path, "navProbList"; 685 686 if ($nextID) { 687 my $nextPage = $urlpath->newFromModule(__PACKAGE__, 688 courseID => $courseID, setID => $setID, problemID => $nextID); 689 push @links, "Next Problem", $r->location . $nextPage->path, "navNext"; 690 } else { 691 push @links, "Next Problem", "", "navNext"; 692 } 693 694 my $tail = "&displayMode=".$self->{displayMode}."&showOldAnswers=".$self->{will}->{showOldAnswers}; 695 return $self->navMacro($args, $tail, @links); 696 } 697 698 sub title { 699 my ($self) = @_; 700 701 # using the url arguments won't break if the set/problem are invalid 702 my $setID = $self->r->urlpath->arg("setID"); 703 my $problemID = $self->r->urlpath->arg("problemID"); 704 705 return "$setID: Problem $problemID"; 706 } 707 708 sub body { 709 my $self = shift; 710 my $r = $self->r; 711 my $ce = $r->ce; 712 my $db = $r->db; 713 my $authz = $r->authz; 714 my $urlpath = $r->urlpath; 715 my $user = $r->param('user'); 716 my $effectiveUser = $r->param('effectiveUser'); 717 718 if ($self->{invalidSet}) { 719 return CGI::div({class=>"ResultsWithError"}, 720 CGI::p("The selected problem set (" . $urlpath->arg("setID") . ") is not a valid set for " . $r->param("effectiveUser") . ".")); 721 } 722 723 if ($self->{invalidProblem}) { 724 return CGI::div({class=>"ResultsWithError"}, 725 CGI::p("The selected problem (" . $urlpath->arg("problemID") . ") is not a valid problem for set " . $self->{set}->set_id . ".")); 726 } 727 728 unless ($self->{isOpen}) { 729 return CGI::div({class=>"ResultsWithError"}, 730 CGI::p("This problem is not available because the problem set that contains it is not yet open.")); 731 } 732 # unpack some useful variables 733 my $set = $self->{set}; 734 my $problem = $self->{problem}; 735 my $editMode = $self->{editMode}; 736 my $submitAnswers = $self->{submitAnswers}; 737 my $checkAnswers = $self->{checkAnswers}; 738 my $previewAnswers = $self->{previewAnswers}; 739 my %want = %{ $self->{want} }; 740 my %can = %{ $self->{can} }; 741 my %must = %{ $self->{must} }; 742 my %will = %{ $self->{will} }; 743 my $pg = $self->{pg}; 744 745 my $courseName = $urlpath->arg("courseID"); 746 747 # FIXME: move editor link to top, next to problem number. 748 # format as "[edit]" like we're doing with course info file, etc. 749 # add edit link for set as well. 750 my $editorLink = ""; 751 # if we are here without a real problem set, carry that through 752 my $forced_field = []; 753 $forced_field = ['sourceFilePath' => $r->param("sourceFilePath")] if 754 ($set->set_id eq 'Undefined_Set'); 755 if ($authz->hasPermissions($user, "modify_problem_sets")) { 756 my $editorPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::PGProblemEditor", 757 courseID => $courseName, setID => $set->set_id, problemID => $problem->problem_id); 758 my $editorURL = $self->systemLink($editorPage, params=>$forced_field); 759 $editorLink = CGI::a({href=>$editorURL}, "Edit this problem"); 760 } 761 762 ##### translation errors? ##### 763 764 if ($pg->{flags}->{error_flag}) { 765 print $self->errorOutput($pg->{errors}, $pg->{body_text}); 766 print $editorLink; 767 return ""; 768 } 769 770 ##### answer processing ##### 771 $WeBWorK::timer->continue("begin answer processing") if defined($WeBWorK::timer); 772 # if answers were submitted: 773 my $scoreRecordedMessage; 774 my $pureProblem; 775 if ($submitAnswers) { 776 # get a "pure" (unmerged) UserProblem to modify 777 # this will be undefined if the problem has not been assigned to this user 778 $pureProblem = $db->getUserProblem($problem->user_id, $problem->set_id, $problem->problem_id); # checked 779 if (defined $pureProblem) { 780 # store answers in DB for sticky answers 781 my %answersToStore; 782 my %answerHash = %{ $pg->{answers} }; 783 $answersToStore{$_} = $self->{formFields}->{$_} #$answerHash{$_}->{original_student_ans} -- this may have been modified for fields with multiple values. Don't use it!! 784 foreach (keys %answerHash); 785 786 # There may be some more answers to store -- one which are auxiliary entries to a primary answer. Evaluating 787 # matrices works in this way, only the first answer triggers an answer evaluator, the rest are just inputs 788 # however we need to store them. Fortunately they are still in the input form. 789 my @extra_answer_names = @{ $pg->{flags}->{KEPT_EXTRA_ANSWERS}}; 790 $answersToStore{$_} = $self->{formFields}->{$_} foreach (@extra_answer_names); 791 792 # Now let's encode these answers to store them -- append the extra answers to the end of answer entry order 793 my @answer_order = (@{$pg->{flags}->{ANSWER_ENTRY_ORDER}}, @extra_answer_names); 794 my $answerString = encodeAnswers(%answersToStore, 795 @answer_order); 796 797 # store last answer to database 798 $problem->last_answer($answerString); 799 $pureProblem->last_answer($answerString); 800 $db->putUserProblem($pureProblem); 801 802 # store state in DB if it makes sense 803 if ($will{recordAnswers}) { 804 $problem->status($pg->{state}->{recorded_score}); 805 $problem->attempted(1); 806 $problem->num_correct($pg->{state}->{num_of_correct_ans}); 807 $problem->num_incorrect($pg->{state}->{num_of_incorrect_ans}); 808 $pureProblem->status($pg->{state}->{recorded_score}); 809 $pureProblem->attempted(1); 810 $pureProblem->num_correct($pg->{state}->{num_of_correct_ans}); 811 $pureProblem->num_incorrect($pg->{state}->{num_of_incorrect_ans}); 812 if ($db->putUserProblem($pureProblem)) { 813 $scoreRecordedMessage = "Your score was recorded."; 814 } else { 815 $scoreRecordedMessage = "Your score was not recorded because there was a failure in storing the problem record to the database."; 816 } 817 # write to the transaction log, just to make sure 818 writeLog($self->{ce}, "transaction", 819 $problem->problem_id."\t". 820 $problem->set_id."\t". 821 $problem->user_id."\t". 822 $problem->source_file."\t". 823 $problem->value."\t". 824 $problem->max_attempts."\t". 825 $problem->problem_seed."\t". 826 $pureProblem->status."\t". 827 $pureProblem->attempted."\t". 828 $pureProblem->last_answer."\t". 829 $pureProblem->num_correct."\t". 830 $pureProblem->num_incorrect 831 ); 832 } else { 833 if (before($set->open_date) or after($set->due_date)) { 834 $scoreRecordedMessage = "Your score was not recorded because this problem set is closed."; 835 } else { 836 $scoreRecordedMessage = "Your score was not recorded."; 837 } 838 } 839 } else { 840 $scoreRecordedMessage = "Your score was not recorded because this problem has not been assigned to you."; 841 } 842 } 843 844 # logging student answers 845 846 my $answer_log = $self->{ce}->{courseFiles}->{logs}->{'answer_log'}; 847 if ( defined($answer_log ) and defined($pureProblem)) { 848 if ($submitAnswers && !$authz->hasPermissions($effectiveUser, "dont_log_past_answers")) { 849 my $answerString = ""; my $scores = ""; 850 my %answerHash = %{ $pg->{answers} }; 851 # FIXME this is the line 552 error. make sure original student ans is defined. 852 # The fact that it is not defined is probably due to an error in some answer evaluator. 853 # But I think it is useful to suppress this error message in the log. 854 foreach (sort keys %answerHash) { 855 my $orig_ans = $answerHash{$_}->{original_student_ans}; 856 my $student_ans = defined $orig_ans ? $orig_ans : ''; 857 $answerString .= $student_ans."\t"; 858 $scores .= $answerHash{$_}->{score} >= 1 ? "1" : "0"; 859 } 860 $answerString = '' unless defined($answerString); # insure string is defined. 861 writeCourseLog($self->{ce}, "answer_log", 862 join("", 863 '|', $problem->user_id, 864 '|', $problem->set_id, 865 '|', $problem->problem_id, 866 '|', $scores, "\t", 867 time(),"\t", 868 $answerString, 869 ), 870 ); 871 872 } 873 } 874 875 $WeBWorK::timer->continue("end answer processing") if defined($WeBWorK::timer); 876 877 ##### output ##### 878 # custom message for editor 879 if ($authz->hasPermissions($user, "modify_problem_sets") and defined $editMode) { 880 if ($editMode eq "temporaryFile") { 881 print CGI::p(CGI::div({class=>'temporaryFile'}, "Viewing temporary file: ", $problem->source_file)); 882 } elsif ($editMode eq "savedFile") { 883 # taken care of in the initialization phase 884 } 885 } 886 print CGI::start_div({class=>"problemHeader"}); 887 888 889 890 # attempt summary 891 #FIXME -- the following is a kludge: if showPartialCorrectAnswers is negative don't show anything. 892 # until after the due date 893 # do I need to check $will{showCorrectAnswers} to make preflight work?? 894 if (($pg->{flags}->{showPartialCorrectAnswers} >= 0 and $submitAnswers) ) { 895 # print this if user submitted answers OR requested correct answers 896 897 print $self->attemptResults($pg, 1, 898 $will{showCorrectAnswers}, 899 $pg->{flags}->{showPartialCorrectAnswers}, 1, 1); 900 } elsif ($checkAnswers) { 901 # print this if user previewed answers 902 print CGI::div({class=>'ResultsWithError'},"ANSWERS ONLY CHECKED -- ANSWERS NOT RECORDED"), CGI::br(); 903 print $self->attemptResults($pg, 1, $will{showCorrectAnswers}, 1, 1, 1); 904 # show attempt answers 905 # show correct answers if asked 906 # show attempt results (correctness) 907 # show attempt previews 908 } elsif ($previewAnswers) { 909 # print this if user previewed answers 910 print CGI::div({class=>'ResultsWithError'},"PREVIEW ONLY -- ANSWERS NOT RECORDED"),CGI::br(),$self->attemptResults($pg, 1, 0, 0, 0, 1); 911 # show attempt answers 912 # don't show correct answers 913 # don't show attempt results (correctness) 914 # show attempt previews 915 } 916 917 print CGI::end_div(); 918 919 # main form 920 print CGI::startform("POST", $r->uri); 921 print $self->hidden_authen_fields; 922 923 print CGI::start_div({class=>"problem"}); 924 print CGI::p($pg->{body_text}); 925 print CGI::p(CGI::b("Note: "), CGI::i($pg->{result}->{msg})) if $pg->{result}->{msg}; 926 print CGI::end_div(); 927 928 print CGI::start_p(); 929 930 if ($can{showCorrectAnswers}) { 931 print CGI::checkbox( 932 -name => "showCorrectAnswers", 933 -checked => $will{showCorrectAnswers}, 934 -label => "Show correct answers", 935 ); 936 } 937 if ($can{showHints}) { 938 print CGI::div({style=>"color:red"}, 939 CGI::checkbox( 940 -name => "showHints", 941 -checked => $will{showHints}, 942 -label => "Show Hints", 943 ) 944 ); 945 } 946 if ($can{showSolutions}) { 947 print CGI::checkbox( 948 -name => "showSolutions", 949 -checked => $will{showSolutions}, 950 -label => "Show Solutions", 951 ); 952 } 953 954 if ($can{showCorrectAnswers} or $can{showHints} or $can{showSolutions}) { 955 print CGI::br(); 956 } 957 958 print CGI::submit(-name=>"previewAnswers", -label=>"Preview Answers"); 959 if ($can{checkAnswers}) { 960 print CGI::submit(-name=>"checkAnswers", -label=>"Check Answers"); 961 } 962 if ($can{getSubmitButton}) { 963 if ($user ne $effectiveUser) { 964 # if acting as a student, make it clear that answer submissions will 965 # apply to the student's records, not the professor's. 966 print CGI::submit(-name=>"submitAnswers", -label=>"Submit Answers for $effectiveUser"); 967 } else { 968 print CGI::submit(-name=>"submitAnswers", -label=>"Submit Answers"); 969 } 970 } 971 972 print CGI::end_p(); 973 974 print CGI::start_div({class=>"scoreSummary"}); 975 976 # score summary 977 my $attempts = $problem->num_correct + $problem->num_incorrect; 978 my $attemptsNoun = $attempts != 1 ? "times" : "time"; 979 my $problem_status = $problem->status || 0; 980 my $lastScore = sprintf("%.0f%%", $problem_status * 100); # Round to whole number 981 my ($attemptsLeft, $attemptsLeftNoun); 982 if ($problem->max_attempts == -1) { 983 # unlimited attempts 984 $attemptsLeft = "unlimited"; 985 $attemptsLeftNoun = "attempts"; 986 } else { 987 $attemptsLeft = $problem->max_attempts - $attempts; 988 $attemptsLeftNoun = $attemptsLeft == 1 ? "attempt" : "attempts"; 989 } 990 991 my $setClosed = 0; 992 my $setClosedMessage; 993 if (before($set->open_date) or after($set->due_date)) { 994 $setClosed = 1; 995 if (before($set->open_date)) { 996 $setClosedMessage = "This problem set is not yet open."; 997 } elsif (after($set->due_date)) { 998 $setClosedMessage = "This problem set is closed."; 999 } 1000 } 1001 #if (before($set->open_date) or after($set->due_date)) { 1002 # $setClosed = 1; 1003 # $setClosedMessage = "This problem set is closed."; 1004 # if ($authz->hasPermissions($user, "view_answers")) { 1005 # $setClosedMessage .= " However, since you are a privileged user, additional attempts will be recorded."; 1006 # } else { 1007 # $setClosedMessage .= " Additional attempts will not be recorded."; 1008 # } 1009 #} 1010 1011 my $notCountedMessage = ($problem->value) ? "" : "(This problem will not count towards your grade.)"; 1012 print CGI::p( 1013 $submitAnswers ? $scoreRecordedMessage . CGI::br() : "", 1014 "You have attempted this problem $attempts $attemptsNoun.", CGI::br(), 1015 $problem->attempted 1016 ? "Your recorded score is $lastScore. $notCountedMessage" . CGI::br() 1017 : "", 1018 $setClosed ? $setClosedMessage : "You have $attemptsLeft $attemptsLeftNoun remaining." 1019 ); 1020 print CGI::end_div(); 1021 1022 # save state for viewOptions 1023 print CGI::hidden( 1024 -name => "showOldAnswers", 1025 -value => $will{showOldAnswers} 1026 ), 1027 1028 CGI::hidden( 1029 -name => "displayMode", 1030 -value => $self->{displayMode} 1031 ); 1032 print( CGI::hidden( 1033 -name => 'editMode', 1034 -value => $self->{editMode}, 1035 ) 1036 ) if defined($self->{editMode}) and $self->{editMode} eq 'temporaryFile'; 1037 print( CGI::hidden( 1038 -name => 'sourceFilePath', 1039 -value => $self->{problem}->{source_file} 1040 )) if defined($self->{problem}->{source_file}); 1041 1042 print( CGI::hidden( 1043 -name => 'problemSeed', 1044 -value => $r->param("problemSeed") 1045 )) if defined($r->param("problemSeed")); 1046 1047 # end of main form 1048 print CGI::endform(); 1049 1050 print CGI::start_div({class=>"problemFooter"}); 1051 1052 ## arguments for answer inspection button 1053 #my $prof_url = $ce->{webworkURLs}->{oldProf}; 1054 #my $webworkURL = $ce->{webworkURLs}->{root}; 1055 #my $cgi_url = $prof_url; 1056 #$cgi_url=~ s|/[^/]*$||; # clip profLogin.pl 1057 #my $authen_args = $self->url_authen_args(); 1058 #my $showPastAnswersURL = "$webworkURL/$courseName/instructor/show_answers/"; 1059 1060 my $pastAnswersPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::ShowAnswers", 1061 courseID => $courseName); 1062 my $showPastAnswersURL = $self->systemLink($pastAnswersPage, authen => 0); # no authen info for form action 1063 1064 # print answer inspection button 1065 if ($authz->hasPermissions($user, "view_answers")) { 1066 print "\n", 1067 CGI::start_form(-method=>"POST",-action=>$showPastAnswersURL,-target=>"information"),"\n", 1068 $self->hidden_authen_fields,"\n", 1069 CGI::hidden(-name => 'courseID', -value=>$courseName), "\n", 1070 CGI::hidden(-name => 'problemID', -value=>$problem->problem_id), "\n", 1071 CGI::hidden(-name => 'setID', -value=>$problem->set_id), "\n", 1072 CGI::hidden(-name => 'studentUser', -value=>$problem->user_id), "\n", 1073 CGI::p( {-align=>"left"}, 1074 CGI::submit(-name => 'action', -value=>'Show Past Answers') 1075 ), "\n", 1076 CGI::endform(); 1077 } 1078 1079 # feedback form url 1080 my $feedbackPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Feedback", 1081 courseID => $courseName); 1082 my $feedbackURL = $self->systemLink($feedbackPage, authen => 0); # no authen info for form action 1083 1084 #print feedback form 1085 print 1086 CGI::start_form(-method=>"POST", -action=>$feedbackURL),"\n", 1087 $self->hidden_authen_fields,"\n", 1088 CGI::hidden("module", __PACKAGE__),"\n", 1089 CGI::hidden("set", $set->set_id),"\n", 1090 CGI::hidden("problem", $problem->problem_id),"\n", 1091 CGI::hidden("displayMode", $self->{displayMode}),"\n", 1092 CGI::hidden("showOldAnswers", $will{showOldAnswers}),"\n", 1093 CGI::hidden("showCorrectAnswers", $will{showCorrectAnswers}),"\n", 1094 CGI::hidden("showHints", $will{showHints}),"\n", 1095 CGI::hidden("showSolutions", $will{showSolutions}),"\n", 1096 CGI::p({-align=>"left"}, 1097 CGI::submit(-name=>"feedbackForm", -label=>"Email instructor") 1098 ), 1099 CGI::endform(),"\n"; 1100 1101 # FIXME print editor link 1102 print $editorLink; #empty unless it is appropriate to have an editor link. 1103 1104 print CGI::end_div(); 1105 1106 # debugging stuff 1107 if (0) { 1108 print 1109 CGI::hr(), 1110 CGI::h2("debugging information"), 1111 CGI::h3("form fields"), 1112 ref2string($self->{formFields}), 1113 CGI::h3("user object"), 1114 ref2string($self->{user}), 1115 CGI::h3("set object"), 1116 ref2string($set), 1117 CGI::h3("problem object"), 1118 ref2string($problem), 1119 CGI::h3("PG object"), 1120 ref2string($pg, {'WeBWorK::PG::Translator' => 1}); 1121 } 1122 1123 return ""; 1124 } 1125 1126 1;
| aubreyja at gmail dot com | ViewVC Help |
| Powered by ViewVC 1.0.9 |