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