Parent Directory
|
Revision Log
Cleaning up commented out code. Added a "due date is...." message to the top of the ProblemSet page.
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.114 2004/02/04 13:22:56 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 38 39 ############################################################ 40 # 41 # user 42 # effectiveUser 43 # key 44 # 45 # displayMode 46 # showOldAnswers 47 # showCorrectAnswers 48 # showHints 49 # showSolutions 50 # 51 # AnSwEr# - answer blanks in problem 52 # 53 # redisplay - name of the "Redisplay Problem" button 54 # submitAnswers - name of "Submit Answers" button 55 # checkAnswers - name of the "Check Answers" button 56 # previewAnswers - name of the "Preview Answers" button 57 # 58 # FIXME: this table is heinously out of date 59 # 60 ############################################################ 61 62 # FIXME: what is this? 63 sub templateName { 64 "problem"; 65 } 66 67 sub pre_header_initialize { 68 my ($self, $setName, $problemNumber) = @_; 69 my $r = $self->{r}; 70 my $courseEnv = $self->{ce}; 71 my $db = $self->{db}; 72 my $userName = $r->param('user'); 73 my $effectiveUserName = $r->param('effectiveUser'); 74 my $key = $r->param('key'); 75 76 my $user = $db->getUser($userName); # checked 77 die "record for user $userName (real user) does not exist." 78 unless defined $user; 79 80 my $effectiveUser = $db->getUser($effectiveUserName); # checked 81 die "record for user $effectiveUserName (effective user) does not exist." 82 unless defined $effectiveUser; 83 84 my $PermissionLevel = $db->getPermissionLevel($userName); # checked 85 die "permission level record for user $userName does not exist (but the user does? odd...)" 86 unless defined $PermissionLevel; 87 my $permissionLevel = $PermissionLevel->permission; 88 89 # obtain the merged set for $effectiveUser 90 my $set = $db->getMergedSet($effectiveUserName, $setName); # checked 91 92 # obtain the merged problem for $effectiveUser 93 my $problem = $db->getMergedProblem($effectiveUserName, $setName, $problemNumber); # checked 94 95 my $editMode = $r->param("editMode"); 96 97 if ($permissionLevel > 0 and defined $editMode) { 98 # professors are allowed to fabricate sets and problems not 99 # assigned to them (or anyone). this allows them to use the 100 # editor to 101 102 # if that is not yet defined obtain the global set, convert 103 # it to a user set, and add fake user data 104 unless (defined $set) { 105 my $userSetClass = $db->{set_user}->{record}; 106 my $globalSet = $db->getGlobalSet($setName); # checked 107 # if the global set doesn't exist either, bail! 108 die "Set $setName does not exist" 109 unless defined $set; 110 $set = global2user($userSetClass, $globalSet); 111 $set->psvn(0); 112 } 113 114 # if that is not yet defined obtain the global problem, 115 # convert it to a user problem, and add fake user data 116 unless (defined $problem) { 117 my $userProblemClass = $db->{problem_user}->{record}; 118 my $globalProblem = $db->getGlobalProblem($setName, $problemNumber); # checked 119 # if the global problem doesn't exist either, bail! 120 die "Problem $problemNumber in set $setName does not exist" 121 unless defined $problem; 122 $problem = global2user($userProblemClass, $globalProblem); 123 $problem->user_id($effectiveUserName); 124 $problem->problem_seed(0); 125 $problem->status(0); 126 $problem->attempted(0); 127 $problem->last_answer(""); 128 $problem->num_correct(0); 129 $problem->num_incorrect(0); 130 } 131 132 # now we're sure we have valid UserSet and UserProblem objects 133 # yay! 134 135 # now deal with possible editor overrides: 136 137 # if the caller is asking to override the source file, and 138 # editMode calls for a temporary file, do so 139 my $sourceFilePath = $r->param("sourceFilePath"); 140 if (defined $sourceFilePath and $editMode eq "temporaryFile") { 141 $problem->source_file($sourceFilePath); 142 } 143 144 # if the caller is asking to override the problem seed, do so 145 my $problemSeed = $r->param("problemSeed"); 146 if (defined $problemSeed) { 147 $problem->problem_seed($problemSeed); 148 } 149 } else { 150 # students can't view problems not assigned to them 151 die "Set $setName is not assigned to $effectiveUserName" 152 unless defined $set; 153 die "Problem $problemNumber in set $setName is not assigned to $effectiveUserName" 154 unless defined $problem; 155 } 156 157 $self->{userName} = $userName; 158 $self->{effectiveUserName} = $effectiveUserName; 159 $self->{user} = $user; 160 $self->{effectiveUser} = $effectiveUser; 161 $self->{permissionLevel} = $permissionLevel; 162 $self->{set} = $set; 163 $self->{problem} = $problem; 164 $self->{editMode} = $editMode; 165 166 ##### form processing ##### 167 168 # set options from form fields (see comment at top of file for names) 169 my $displayMode = $r->param("displayMode") || $courseEnv->{pg}->{options}->{displayMode}; 170 my $redisplay = $r->param("redisplay"); 171 my $submitAnswers = $r->param("submitAnswers"); 172 my $checkAnswers = $r->param("checkAnswers"); 173 my $previewAnswers = $r->param("previewAnswers"); 174 175 176 my $formFields = { WeBWorK::Form->new_from_paramable($r)->Vars }; 177 178 179 $self->{displayMode} = $displayMode; 180 $self->{redisplay} = $redisplay; 181 $self->{submitAnswers} = $submitAnswers; 182 $self->{checkAnswers} = $checkAnswers; 183 $self->{previewAnswers} = $previewAnswers; 184 $self->{formFields} = $formFields; 185 186 ##### permissions ##### 187 188 # are we allowed to view this problem? 189 $self->{isOpen} = time >= $set->open_date || $permissionLevel > 0; 190 return unless $self->{isOpen}; 191 192 # what does the user want to do? 193 my %want = ( 194 showOldAnswers => $r->param("showOldAnswers") || $courseEnv->{pg}->{options}->{showOldAnswers}, 195 showCorrectAnswers => $r->param("showCorrectAnswers") || $courseEnv->{pg}->{options}->{showCorrectAnswers}, 196 showHints => $r->param("showHints") || $courseEnv->{pg}->{options}->{showHints}, 197 showSolutions => $r->param("showSolutions") || $courseEnv->{pg}->{options}->{showSolutions}, 198 recordAnswers => $submitAnswers, 199 checkAnswers => $checkAnswers, 200 ); 201 202 # are certain options enforced? 203 my %must = ( 204 showOldAnswers => 0, 205 showCorrectAnswers => 0, 206 showHints => 0, 207 showSolutions => 0, 208 recordAnswers => mustRecordAnswers($permissionLevel), 209 checkAnswers => 0, 210 ); 211 212 # does the user have permission to use certain options? 213 my %can = ( 214 showOldAnswers => 1, 215 showCorrectAnswers => canShowCorrectAnswers($permissionLevel, $set->answer_date), 216 showHints => 1, 217 showSolutions => canShowSolutions($permissionLevel, $set->answer_date), 218 recordAnswers => canRecordAnswers($permissionLevel, $set->open_date, $set->due_date, 219 $problem->max_attempts, $problem->num_correct + $problem->num_incorrect + 1), 220 # attempts=num_correct+num_incorrect+1, as this happens before updating $problem 221 checkAnswers => canCheckAnswers($permissionLevel, $set->answer_date), 222 ); 223 ######################################################### 224 # more complicated logic for showing check answer button: 225 ######################################################### 226 # checkAnswers button shows up after due date -- once a student can't record anymore 227 # checkAnswers button always shows up when an instructor or TA is acting 228 # as someone else (the $user and $effectiveUserName aren't the same). 229 $can{checkAnswers} = ($can{checkAnswers} && not $can{recordAnswers} ) || 230 ( defined($userName) and defined($effectiveUserName) and 231 ($userName ne $effectiveUserName) 232 ); 233 ######################################################### 234 # more complicated logif for showing "submit answer" button 235 ######################################################### 236 # We hide the submit answer button if someone is acting as a student 237 # This prevents errors where you accidently submit the answer for a student 238 # Not sure whether this a feature or a bug 239 240 $can{recordAnswers} = ($can{recordAnswers} and not 241 ( defined($userName) and defined($effectiveUserName) and 242 ($userName ne $effectiveUserName) 243 ) 244 ); 245 # final values for options 246 my %will; 247 foreach (keys %must) { 248 $will{$_} = $can{$_} && ($want{$_} || $must{$_}); 249 } 250 251 ##### sticky answers ##### 252 253 if (not ($submitAnswers or $previewAnswers or $checkAnswers) and $will{showOldAnswers}) { 254 # do this only if new answers are NOT being submitted 255 my %oldAnswers = decodeAnswers($problem->last_answer); 256 $formFields->{$_} = $oldAnswers{$_} foreach keys %oldAnswers; 257 } 258 259 ##### translation ##### 260 261 $WeBWorK::timer->continue("begin pg processing") if defined($WeBWorK::timer); 262 my $pg = WeBWorK::PG->new( 263 $courseEnv, 264 $effectiveUser, 265 $key, 266 $set, 267 $problem, 268 $set->psvn, # FIXME: this field should be removed 269 $formFields, 270 { # translation options 271 displayMode => $displayMode, 272 showHints => $will{showHints}, 273 showSolutions => $will{showSolutions}, 274 refreshMath2img => $will{showHints} || $will{showSolutions}, 275 processAnswers => 1, 276 }, 277 ); 278 279 $WeBWorK::timer->continue("end pg processing") if defined($WeBWorK::timer); 280 ##### fix hint/solution options ##### 281 282 $can{showHints} &&= $pg->{flags}->{hintExists} 283 &&= $pg->{flags}->{showHintLimit}<=$pg->{state}->{num_of_incorrect_ans}; 284 $can{showSolutions} &&= $pg->{flags}->{solutionExists}; 285 286 ##### store fields ##### 287 288 $self->{want} = \%want; 289 $self->{must} = \%must; 290 $self->{can} = \%can; 291 $self->{will} = \%will; 292 $self->{pg} = $pg; 293 } 294 295 #sub if_warnings($$) { 296 # my ($self, $arg) = @_; 297 # return 0 unless $self->{isOpen}; 298 # return $self->{pg}->{warnings} ne ""; 299 #} 300 301 sub if_errors($$) { 302 my ($self, $arg) = @_; 303 return 0 unless $self->{isOpen}; 304 return $self->{pg}->{flags}->{error_flag}; 305 } 306 307 sub head { 308 my $self = shift; 309 return "" unless $self->{isOpen}; 310 return $self->{pg}->{head_text} if $self->{pg}->{head_text}; 311 } 312 313 sub options { 314 my $self = shift; 315 return join("", 316 CGI::start_form("POST", $self->{r}->uri), 317 $self->hidden_authen_fields, 318 CGI::hr(), 319 CGI::start_div({class=>"viewOptions"}), 320 $self->viewOptions(), 321 CGI::end_div(), 322 CGI::end_form() 323 ); 324 } 325 326 sub path { 327 my $self = shift; 328 my $args = $_[-1]; 329 my $setName = $self->{set}->set_id; 330 my $problemNumber = $self->{problem}->problem_id; 331 332 my $ce = $self->{ce}; 333 my $root = $ce->{webworkURLs}->{root}; 334 my $courseName = $ce->{courseName}; 335 return $self->pathMacro($args, 336 "Home" => "$root", 337 $courseName => "$root/$courseName", 338 $setName => "$root/$courseName/$setName", 339 "Problem $problemNumber" => "", 340 ); 341 } 342 343 sub siblings { 344 my $self = shift; 345 my $setName = $self->{set}->set_id; 346 my $problemNumber = $self->{problem}->problem_id; 347 348 my $ce = $self->{ce}; 349 my $db = $self->{db}; 350 my $root = $ce->{webworkURLs}->{root}; 351 my $courseName = $ce->{courseName}; 352 print CGI::strong("Problems"), CGI::br(); 353 354 my $effectiveUser = $self->{r}->param("effectiveUser"); 355 my @problemIDs = $db->listUserProblems($effectiveUser, $setName); 356 foreach my $problem (sort { $a <=> $b } @problemIDs) { 357 print ' '.CGI::a({-href=>"$root/$courseName/$setName/".$problem."/?" 358 . $self->url_authen_args . "&displayMode=" . $self->{displayMode}}, 359 "Problem ".$problem), CGI::br(); 360 } 361 362 return ""; 363 } 364 365 sub nav { 366 $WeBWorK::timer->continue("begin nav subroutine") if defined($WeBWorK::timer); 367 my $self = shift; 368 my $args = $_[-1]; 369 my $setName = $self->{set}->set_id; 370 my $problemNumber = $self->{problem}->problem_id; 371 372 my $ce = $self->{ce}; 373 my $db = $self->{db}; 374 my $root = $ce->{webworkURLs}->{root}; 375 my $courseName = $ce->{courseName}; 376 377 my $wwdb = $self->{wwdb}; 378 my $effectiveUser = $self->{r}->param("effectiveUser"); 379 my $tail = "&displayMode=".$self->{displayMode}; 380 381 my @links = ("Problem List" , "$root/$courseName/$setName", "navProbList"); 382 383 my @problemIDs = $db->listUserProblems($effectiveUser, $setName); 384 my ($prevID, $nextID); 385 foreach my $id (@problemIDs) { 386 $prevID = $id if $id < $problemNumber 387 and (not defined $prevID or $id > $prevID); 388 $nextID = $id if $id > $problemNumber 389 and (not defined $nextID or $id < $nextID); 390 } 391 unshift @links, "Previous Problem" , ($prevID 392 ? "$root/$courseName/$setName/".$prevID 393 : "") , "navPrev"; 394 push @links, "Next Problem" , ($nextID 395 ? "$root/$courseName/$setName/".$nextID 396 : "") , "navNext"; 397 398 my $result = $self->navMacro($args, $tail, @links); 399 $WeBWorK::timer->continue("end nav subroutine") if defined($WeBWorK::timer); 400 return $result; 401 } 402 403 sub title { 404 my $self = shift; 405 my $setName = $self->{set}->set_id; 406 my $problemNumber = $self->{problem}->problem_id; 407 408 return "$setName : Problem $problemNumber"; 409 } 410 411 sub body { 412 my $self = shift; 413 414 return CGI::p(CGI::font({-color=>"red"}, "This problem is not available because the problem set that contains it is not yet open.")) 415 unless $self->{isOpen}; 416 417 # unpack some useful variables 418 my $r = $self->{r}; 419 my $db = $self->{db}; 420 my $ce = $self->{ce}; 421 my $root = $ce->{webworkURLs}->{root}; 422 my $courseName = $ce->{courseName}; 423 my $set = $self->{set}; 424 my $problem = $self->{problem}; 425 my $editMode = $self->{editMode}; 426 my $permissionLevel = $self->{permissionLevel}; 427 my $submitAnswers = $self->{submitAnswers}; 428 my $checkAnswers = $self->{checkAnswers}; 429 my $previewAnswers = $self->{previewAnswers}; 430 my %want = %{ $self->{want} }; 431 my %can = %{ $self->{can} }; 432 my %must = %{ $self->{must} }; 433 my %will = %{ $self->{will} }; 434 my $pg = $self->{pg}; 435 436 437 438 #####create Editor link ##### 439 # print editor link if the user is an instructor AND the file is not in temporary editing mode 440 my $editorLinkMessage = ''; 441 # and ( (not defined($self->{editMode})) or $self->{editMode} eq 'savedFile') # FIXME is this needed? 442 if ($self->{permissionLevel}>=10 ) { 443 $editorLinkMessage = CGI::a({-href=>$ce->{webworkURLs}->{root}."/$courseName/instructor/pgProblemEditor/". 444 $set->set_id.'/'.$problem->problem_id.'?'.$self->url_authen_args},'Edit this problem'); 445 } 446 ##### translation errors? ##### 447 448 if ($pg->{flags}->{error_flag}) { 449 return $self->errorOutput($pg->{errors}, $pg->{body_text}.CGI::p($editorLinkMessage)); 450 } 451 452 ##### answer processing ##### 453 $WeBWorK::timer->continue("begin answer processing") if defined($WeBWorK::timer); 454 # if answers were submitted: 455 my $scoreRecordedMessage; 456 if ($submitAnswers) { 457 # get a "pure" (unmerged) UserProblem to modify 458 # this will be undefined if the problem has not been assigned to this user 459 my $pureProblem = $db->getUserProblem($problem->user_id, $problem->set_id, $problem->problem_id); # checked 460 if (defined $pureProblem) { 461 # store answers in DB for sticky answers 462 my %answersToStore; 463 my %answerHash = %{ $pg->{answers} }; 464 $answersToStore{$_} = $self->{formFields}->{$_} #$answerHash{$_}->{original_student_ans} -- this may have been modified for fields with multiple values. Don't use it!! 465 foreach (keys %answerHash); 466 # There may be some more answers to store -- one which are auxiliary entries to a primary answer. Evaluating 467 # matrices works in this way, only the first answer triggers an answer evaluator, the rest are just inputs 468 # however we need to store them. Fortunately they are still in the input form. 469 my @extra_answer_names = @{ $pg->{flags}->{KEPT_EXTRA_ANSWERS}}; 470 471 $answersToStore{$_} = $self->{formFields}->{$_} foreach (@extra_answer_names); 472 473 # Now let's encode these answers to store them -- append the extra answers to the end of answer entry order 474 my @answer_order = (@{$pg->{flags}->{ANSWER_ENTRY_ORDER}}, @extra_answer_names); 475 my $answerString = encodeAnswers(%answersToStore, 476 @answer_order); 477 478 # store last answer to database 479 $problem->last_answer($answerString); 480 $pureProblem->last_answer($answerString); 481 $db->putUserProblem($pureProblem); 482 483 # store state in DB if it makes sense 484 if ($will{recordAnswers}) { 485 $problem->status($pg->{state}->{recorded_score}); 486 $problem->attempted(1); 487 $problem->num_correct($pg->{state}->{num_of_correct_ans}); 488 $problem->num_incorrect($pg->{state}->{num_of_incorrect_ans}); 489 $pureProblem->status($pg->{state}->{recorded_score}); 490 $pureProblem->attempted(1); 491 $pureProblem->num_correct($pg->{state}->{num_of_correct_ans}); 492 $pureProblem->num_incorrect($pg->{state}->{num_of_incorrect_ans}); 493 if ($db->putUserProblem($pureProblem)) { 494 $scoreRecordedMessage = "Your score was recorded."; 495 } else { 496 $scoreRecordedMessage = "Your score was not recorded because there was a failure in storing the problem record to the database."; 497 } 498 # write to the transaction log, just to make sure 499 writeLog($self->{ce}, "transaction", 500 $problem->problem_id."\t". 501 $problem->set_id."\t". 502 $problem->user_id."\t". 503 $problem->source_file."\t". 504 $problem->value."\t". 505 $problem->max_attempts."\t". 506 $problem->problem_seed."\t". 507 $pureProblem->status."\t". 508 $pureProblem->attempted."\t". 509 $pureProblem->last_answer."\t". 510 $pureProblem->num_correct."\t". 511 $pureProblem->num_incorrect 512 ); 513 } else { 514 if (time < $set->open_date or time > $set->due_date) { 515 $scoreRecordedMessage = "Your score was not recorded because this problem set is closed."; 516 } else { 517 $scoreRecordedMessage = "Your score was not recorded."; 518 } 519 } 520 } else { 521 $scoreRecordedMessage = "Your score was not recorded because this problem has not been built for you."; 522 } 523 } 524 525 # logging student answers 526 527 my $answer_log = $self->{ce}->{courseFiles}->{logs}->{'answer_log'}; 528 if ( defined($answer_log )) { 529 if ($submitAnswers ) { 530 my $answerString = ""; 531 my %answerHash = %{ $pg->{answers} }; 532 # FIXME this is the line 552 error. make sure original student ans is defined. 533 # The fact that it is not defined is probably due to an error in some answer evaluator. 534 # But I think it is useful to suppress this error message in the log. 535 foreach (sort keys %answerHash) { 536 my $student_ans = $answerHash{$_}->{original_student_ans} ||''; 537 $answerString .= $student_ans."\t" 538 } 539 $answerString = '' unless defined($answerString); # insure string is defined. 540 writeCourseLog($self->{ce}, "answer_log", 541 join("", 542 '|', $problem->user_id, 543 '|', $problem->set_id, 544 '|', $problem->problem_id, 545 '|',"\t", 546 time(),"\t", 547 $answerString, 548 ), 549 ); 550 551 } 552 } 553 554 $WeBWorK::timer->continue("end answer processing") if defined($WeBWorK::timer); 555 556 ##### output ##### 557 558 print CGI::start_div({class=>"problemHeader"}); 559 560 # custom message for editor 561 if ($permissionLevel >= 10 and defined $editMode) { 562 if ($editMode eq "temporaryFile") { 563 print CGI::p(CGI::i("Editing temporary file: ", $problem->source_file)); 564 } elsif ($editMode eq "savedFile") { 565 print CGI::p(CGI::i("Problem saved to: ", $problem->source_file)); 566 } 567 } 568 569 # attempt summary 570 #FIXME -- the following is a kludge: if showPartialCorrectAnswers is negative don't show anything. 571 # until after the due date 572 # do I need to check $wills{howCorrectAnswers} to make preflight work?? 573 if (($pg->{flags}->{showPartialCorrectAnswers}>= 0 and $submitAnswers) ) { 574 # print this if user submitted answers OR requested correct answers 575 576 print $self->attemptResults($pg, 1, 577 $will{showCorrectAnswers}, 578 $pg->{flags}->{showPartialCorrectAnswers}, 1, 1); 579 } elsif ($checkAnswers) { 580 # print this if user previewed answers 581 print "ANSWERS ONLY CHECKED -- ",CGI::br(),"ANSWERS NOT RECORDED", CGI::br(); 582 print $self->attemptResults($pg, 1, $will{showCorrectAnswers}, 1, 1, 1); 583 # show attempt answers 584 # show correct answers if asked 585 # show attempt results (correctness) 586 # show attempt previews 587 } elsif ($previewAnswers) { 588 # print this if user previewed answers 589 print "PREVIEW ONLY -- NOT RECORDED",CGI::br(),$self->attemptResults($pg, 1, 0, 0, 0, 1); 590 # show attempt answers 591 # don't show correct answers 592 # don't show attempt results (correctness) 593 # show attempt previews 594 } 595 596 print CGI::end_div(); 597 598 print CGI::start_div({class=>"problem"}); 599 600 # main form 601 print 602 CGI::startform("POST", $r->uri), 603 $self->hidden_authen_fields, 604 CGI::p($pg->{body_text}), 605 CGI::p($pg->{result}->{msg} ? CGI::b("Note: ") : "", CGI::i($pg->{result}->{msg})), 606 CGI::p( 607 ($can{showCorrectAnswers} 608 ? CGI::checkbox( 609 -name => "showCorrectAnswers", 610 -checked => $will{showCorrectAnswers}, 611 -label => "Show correct answers", 612 ) ." " 613 : "" ), 614 ($can{showHints} 615 ? '<div style="color:red">'. CGI::checkbox( 616 -name => "showHints", 617 -checked => $will{showHints}, 618 -label => "Show Hints", 619 ) . "</div> " 620 : " " ), 621 ($can{showSolutions} 622 ? CGI::checkbox( 623 -name => "showSolutions", 624 -checked => $will{showSolutions}, 625 -label => "Show Solutions", 626 ) . " " 627 : " " ),CGI::br(), 628 CGI::submit(-name=>"previewAnswers", 629 -label=>"Preview Answers"), 630 ($can{recordAnswers} 631 ? CGI::submit(-name=>"submitAnswers", 632 -label=>"Submit Answers") 633 : ""), 634 ( $can{checkAnswers} 635 ? CGI::submit(-name=>"checkAnswers", 636 -label=>"Check Answers") 637 : ""), 638 ); 639 print CGI::end_div(); 640 641 print CGI::start_div({class=>"scoreSummary"}); 642 643 # score summary 644 my $attempts = $problem->num_correct + $problem->num_incorrect; 645 my $attemptsNoun = $attempts != 1 ? "times" : "time"; 646 my $lastScore = sprintf("%.0f%%", $problem->status * 100); # Round to whole number 647 my ($attemptsLeft, $attemptsLeftNoun); 648 if ($problem->max_attempts == -1) { 649 # unlimited attempts 650 $attemptsLeft = "unlimited"; 651 $attemptsLeftNoun = "attempts"; 652 } else { 653 $attemptsLeft = $problem->max_attempts - $attempts; 654 $attemptsLeftNoun = $attemptsLeft == 1 ? "attempt" : "attempts"; 655 } 656 657 my $setClosed = 0; 658 my $setClosedMessage; 659 if (time < $set->open_date or time > $set->due_date) { 660 $setClosed = 1; 661 $setClosedMessage = "This problem set is closed."; 662 if ($permissionLevel > 0) { 663 $setClosedMessage .= " However, since you are a privileged user, additional attempts will be recorded."; 664 } else { 665 $setClosedMessage .= " Additional attempts will not be recorded."; 666 } 667 } 668 print CGI::p( 669 $submitAnswers ? $scoreRecordedMessage . CGI::br() : "", 670 "You have attempted this problem $attempts $attemptsNoun.", CGI::br(), 671 $problem->attempted 672 ? "Your recorded score is $lastScore." . CGI::br() 673 : "", 674 $setClosed ? $setClosedMessage : "You have $attemptsLeft $attemptsLeftNoun remaining." 675 ); 676 print CGI::end_div(); 677 678 # save state for viewOptions 679 print CGI::hidden( 680 -name => "showOldAnswers", 681 -value => $will{showOldAnswers} 682 ), 683 684 CGI::hidden( 685 -name => "displayMode", 686 -value => $self->{displayMode} 687 ); 688 print( CGI::hidden( 689 -name => 'editMode', 690 -value => $self->{editMode}, 691 ) 692 ) if defined($self->{editMode}) and $self->{editMode} eq 'temporaryFile'; 693 print( CGI::hidden( 694 -name => 'sourceFilePath', 695 -value => $self->{problem}->{source_file} 696 )) if defined($self->{problem}->{source_file}); 697 698 # end of main form 699 print CGI::endform(); 700 701 702 print CGI::start_div({class=>"problemFooter"}); 703 704 # arguments for answer inspection button 705 my $prof_url = $ce->{webworkURLs}->{oldProf}; 706 my $webworkURL = $ce->{webworkURLs}->{root}; 707 my $cgi_url = $prof_url; 708 $cgi_url=~ s|/[^/]*$||; # clip profLogin.pl 709 my $authen_args = $self->url_authen_args(); 710 my $showPastAnswersURL = "$webworkURL/$courseName/instructor/show_answers/"; 711 712 # print answer inspection button 713 if ($self->{permissionLevel} > 0) { 714 print "\n", 715 CGI::start_form(-method=>"POST",-action=>$showPastAnswersURL,-target=>"information"),"\n", 716 $self->hidden_authen_fields,"\n", 717 CGI::hidden(-name => 'course', -value=>$courseName), "\n", 718 CGI::hidden(-name => 'problemNumber', -value=>$problem->problem_id), "\n", 719 CGI::hidden(-name => 'setName', -value=>$problem->set_id), "\n", 720 CGI::hidden(-name => 'studentUser', -value=>$problem->user_id), "\n", 721 CGI::p( {-align=>"left"}, 722 CGI::submit(-name => 'action', -value=>'Show Past Answers') 723 ), "\n", 724 CGI::endform(); 725 } 726 727 #print CGI::end_div(); 728 # 729 #print CGI::start_div(); 730 731 # arguments for feedback form 732 my $feedbackURL = "$root/$courseName/feedback/"; 733 734 #print feedback form 735 print 736 CGI::start_form(-method=>"POST", -action=>$feedbackURL),"\n", 737 $self->hidden_authen_fields,"\n", 738 CGI::hidden("module", __PACKAGE__),"\n", 739 CGI::hidden("set", $set->set_id),"\n", 740 CGI::hidden("problem", $problem->problem_id),"\n", 741 CGI::hidden("displayMode", $self->{displayMode}),"\n", 742 CGI::hidden("showOldAnswers", $will{showOldAnswers}),"\n", 743 CGI::hidden("showCorrectAnswers", $will{showCorrectAnswers}),"\n", 744 CGI::hidden("showHints", $will{showHints}),"\n", 745 CGI::hidden("showSolutions", $will{showSolutions}),"\n", 746 CGI::p({-align=>"left"}, 747 CGI::submit(-name=>"feedbackForm", -label=>"Email instructor") 748 ), 749 CGI::endform(),"\n"; 750 751 # FIXME print editor link 752 print $editorLinkMessage; #empty unless it is appropriate to have an editor link. 753 754 print CGI::end_div(); 755 756 # warning output 757 #if ($pg->{warnings} ne "") { 758 # print CGI::hr(), $self->warningOutput($pg->{warnings}); 759 #} 760 761 # debugging stuff 762 if (0) { 763 print 764 CGI::hr(), 765 CGI::h2("debugging information"), 766 CGI::h3("form fields"), 767 ref2string($self->{formFields}), 768 CGI::h3("user object"), 769 ref2string($self->{user}), 770 CGI::h3("set object"), 771 ref2string($set), 772 CGI::h3("problem object"), 773 ref2string($problem), 774 CGI::h3("PG object"), 775 ref2string($pg, {'WeBWorK::PG::Translator' => 1}); 776 } 777 778 return ""; 779 } 780 781 ##### output utilities ##### 782 783 sub attemptResults($$$$$$) { 784 my $self = shift; 785 my $pg = shift; 786 my $showAttemptAnswers = shift; 787 my $showCorrectAnswers = shift; 788 my $showAttemptResults = $showAttemptAnswers && shift; 789 my $showSummary = shift; 790 my $showAttemptPreview = shift || 0; 791 my $ce = $self->{ce}; 792 my $problemResult = $pg->{result}; # the overall result of the problem 793 my @answerNames = @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} }; 794 795 my $showMessages = $showAttemptAnswers && grep { $pg->{answers}->{$_}->{ans_message} } @answerNames; 796 797 my $basename = "equation-" . $self->{set}->psvn. "." . $self->{problem}->problem_id . "-preview"; 798 my $imgGen = WeBWorK::PG::ImageGenerator->new( 799 tempDir => $ce->{webworkDirs}->{tmp}, 800 latex => $ce->{externalPrograms}->{latex}, 801 dvipng => $ce->{externalPrograms}->{dvipng}, 802 useCache => 1, 803 cacheDir => $ce->{webworkDirs}->{equationCache}, 804 cacheURL => $ce->{webworkURLs}->{equationCache}, 805 cacheDB => $ce->{webworkFiles}->{equationCacheDB}, 806 ); 807 808 my $header; 809 #$header .= CGI::th("Part"); 810 $header .= $showAttemptAnswers ? CGI::th("Entered") : ""; 811 $header .= $showAttemptPreview ? CGI::th("Answer Preview") : ""; 812 $header .= $showCorrectAnswers ? CGI::th("Correct") : ""; 813 $header .= $showAttemptResults ? CGI::th("Result") : ""; 814 $header .= $showMessages ? CGI::th("messages") : ""; 815 my @tableRows = ( $header ); 816 my $numCorrect; 817 foreach my $name (@answerNames) { 818 my $answerResult = $pg->{answers}->{$name}; 819 my $studentAnswer = $answerResult->{student_ans}; # original_student_ans 820 my $preview = ($showAttemptPreview 821 ? $self->previewAnswer($answerResult, $imgGen) 822 : ""); 823 my $correctAnswer = $answerResult->{correct_ans}; 824 my $answerScore = $answerResult->{score}; 825 my $answerMessage = $showMessages ? $answerResult->{ans_message} : ""; 826 #FIXME --Can we be sure that $answerScore is an integer-- could the problem give partial credit? 827 $numCorrect += $answerScore > 0; 828 my $resultString = $answerScore == 1 ? "correct" : "incorrect"; 829 830 # get rid of the goofy prefix on the answer names (supposedly, the format 831 # of the answer names is changeable. this only fixes it for "AnSwEr" 832 #$name =~ s/^AnSwEr//; 833 834 my $row; 835 #$row .= CGI::td($name); 836 $row .= $showAttemptAnswers ? CGI::td(nbsp($studentAnswer)) : ""; 837 $row .= $showAttemptPreview ? CGI::td(nbsp($preview)) : ""; 838 $row .= $showCorrectAnswers ? CGI::td(nbsp($correctAnswer)) : ""; 839 $row .= $showAttemptResults ? CGI::td(nbsp($resultString)) : ""; 840 $row .= $showMessages ? CGI::td(nbsp($answerMessage)) : ""; 841 push @tableRows, $row; 842 } 843 844 # render equation images 845 $imgGen->render(refresh => 1); 846 847 # my $numIncorrectNoun = scalar @answerNames == 1 ? "question" : "questions"; 848 my $scorePercent = sprintf("%.0f%%", $problemResult->{score} * 100); 849 # FIXME -- I left the old code in in case we have to back out. 850 # my $summary = "On this attempt, you answered $numCorrect out of " 851 # . scalar @answerNames . " $numIncorrectNoun correct, for a score of $scorePercent."; 852 my $summary = ""; 853 if (scalar @answerNames == 1) { 854 if ($numCorrect == scalar @answerNames) { 855 $summary .= "The above answer is correct."; 856 } else { 857 $summary .= "The above answer is NOT correct."; 858 } 859 } else { 860 if ($numCorrect == scalar @answerNames) { 861 $summary .= "All of the above answers are correct."; 862 } else { 863 $summary .= "At least one of the above answers is NOT correct."; 864 } 865 } 866 #FIXME there must be a better way to force refresh. 867 #my $refresh_warning = 'Hold down shift and click "refresh" or "reload" to update answer preview images.'; 868 #return CGI::table({-class=>"attemptResults"}, CGI::Tr(\@tableRows)) . 869 #CGI::div({style=>'color:red; font-size:10pt'},$refresh_warning) . 870 #($showSummary ? CGI::p({class=>'emphasis'},$summary) : ""); 871 # ... this has been fixed by equation caching. 872 return 873 CGI::table({-class=>"attemptResults"}, CGI::Tr(\@tableRows)) 874 . ($showSummary ? CGI::p({class=>'emphasis'},$summary) : ""); 875 } 876 sub nbsp { 877 my $str = shift; 878 ($str =~/\S/) ? $str : ' ' ; # returns non-breaking space for empty strings 879 # tricky cases: $str =0; 880 # $str is a complex number 881 } 882 sub viewOptions($) { 883 my $self = shift; 884 my $displayMode = $self->{displayMode}; 885 my %must = %{ $self->{must} }; 886 my %can = %{ $self->{can} }; 887 my %will = %{ $self->{will} }; 888 889 my $optionLine; 890 $can{showOldAnswers} and $optionLine .= join "", 891 "Show: ".CGI::br(), 892 CGI::checkbox( 893 -name => "showOldAnswers", 894 -checked => $will{showOldAnswers}, 895 -label => "Saved answers", 896 ), " ".CGI::br(); 897 898 $optionLine and $optionLine .= join "", CGI::br(); 899 900 return CGI::div({-style=>"border: thin groove; padding: 1ex; margin: 2ex align: left"}, 901 "View equations as: ".CGI::br(), 902 CGI::radio_group( 903 -name => "displayMode", 904 -values => ['plainText', 'formattedText', 'images'], 905 -default => $displayMode, 906 -linebreak=>'true', 907 -labels => { 908 plainText => "plain", 909 formattedText => "formatted", 910 images => "images", 911 } 912 ), CGI::br(),CGI::hr(), 913 $optionLine, 914 CGI::submit(-name=>"redisplay", -label=>"Save Options"), 915 ); 916 } 917 918 sub previewAnswer($$) { 919 my ($self, $answerResult, $imgGen) = @_; 920 my $ce = $self->{ce}; 921 my $effectiveUser = $self->{effectiveUser}; 922 my $set = $self->{set}; 923 my $problem = $self->{problem}; 924 my $displayMode = $self->{displayMode}; 925 926 # note: right now, we have to do things completely differently when we are 927 # rendering math from INSIDE the translator and from OUTSIDE the translator. 928 # so we'll just deal with each case explicitly here. there's some code 929 # duplication that can be dealt with later by abstracting out tth/dvipng/etc. 930 931 my $tex = $answerResult->{preview_latex_string}; 932 933 return "" unless defined $tex and $tex ne ""; 934 935 if ($displayMode eq "plainText") { 936 return $tex; 937 } elsif ($displayMode eq "formattedText") { 938 my $tthCommand = $ce->{externalPrograms}->{tth} 939 . " -L -f5 -r 2> /dev/null <<END_OF_INPUT; echo > /dev/null\n" 940 . "\\(".$tex."\\)\n" 941 . "END_OF_INPUT\n"; 942 943 # call tth 944 my $result = `$tthCommand`; 945 if ($?) { 946 return "<b>[tth failed: $? $@]</b>"; 947 } 948 return $result; 949 } elsif ($displayMode eq "images") { 950 ## how are we going to name this? 951 #my $targetPathCommon = "/m2i/" 952 # . $effectiveUser->user_id . "." 953 # . $set->set_id . "." 954 # . $problem->problem_id . "." 955 # . $answerResult->{ans_name} . ".png"; 956 # 957 ## figure out where to put things 958 #my $wd = makeTempDirectory($ce->{courseDirs}->{html_temp}, "webwork-dvipng"); 959 #my $latex = $ce->{externalPrograms}->{latex}; 960 #my $dvipng = $ce->{externalPrograms}->{dvipng}; 961 #my $targetPath = $ce->{courseDirs}->{html_temp} . $targetPathCommon; 962 # # should use surePathToTmpFile, but we have to 963 # # isolate it from the problem enivronment first 964 #my $targetURL = $ce->{courseURLs}->{html_temp} . $targetPathCommon; 965 # 966 ## call dvipng to generate a preview 967 #dvipng($wd, $latex, $dvipng, $tex, $targetPath); 968 #rmtree($wd, 0, 0); 969 #if (-e $targetPath) { 970 # return "<img src=\"$targetURL\" alt=\"$tex\" />"; 971 #} else { 972 # return "<b>[math2img failed]</b>"; 973 #} 974 $imgGen->add($answerResult->{preview_latex_string}); 975 976 } 977 } 978 979 ##### logging subroutine #### 980 981 982 983 ##### permission queries ##### 984 985 # this stuff should be abstracted out into the permissions system 986 # however, the permission system only knows about things in the 987 # course environment and the username. hmmm... 988 989 # also, i should fix these so that they have a consistent calling 990 # format -- perhaps: 991 # canPERM($courseEnv, $user, $set, $problem, $permissionLevel) 992 993 sub canShowCorrectAnswers($$) { 994 my ($permissionLevel, $answerDate) = @_; 995 return $permissionLevel > 0 || time > $answerDate; 996 } 997 998 sub canShowSolutions($$) { 999 my ($permissionLevel, $answerDate) = @_; 1000 return canShowCorrectAnswers($permissionLevel, $answerDate); 1001 } 1002 1003 sub canRecordAnswers($$$$$) { 1004 my ($permissionLevel, $openDate, $dueDate, $maxAttempts, $attempts) = @_; 1005 my $permHigh = $permissionLevel > 0; 1006 my $timeOK = time >= $openDate && time <= $dueDate; 1007 my $attemptsOK = $maxAttempts == -1 || $attempts <= $maxAttempts; 1008 my $recordAnswers = $permHigh || ($timeOK && $attemptsOK); 1009 return $recordAnswers; 1010 } 1011 1012 sub canCheckAnswers($$) { 1013 my ($permissionLevel, $answerDate) = @_; 1014 my $permHigh = $permissionLevel > 0; 1015 my $timeOK = time >= $answerDate; 1016 my $recordAnswers = $permHigh || $timeOK; 1017 return $recordAnswers; 1018 } 1019 1020 sub mustRecordAnswers($) { 1021 my ($permissionLevel) = @_; 1022 return $permissionLevel == 0; 1023 } 1024 1025 1;
| aubreyja at gmail dot com | ViewVC Help |
| Powered by ViewVC 1.0.9 |