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