################################################################################ # WeBWorK Online Homework Delivery System # Copyright © 2000-2003 The WeBWorK Project, http://openwebwork.sf.net/ # $CVSHeader: webwork-modperl/lib/WeBWorK/ContentGenerator/Problem.pm,v 1.121 2004/04/07 22:18:46 gage Exp $ # # This program is free software; you can redistribute it and/or modify it under # the terms of either: (a) the GNU General Public License as published by the # Free Software Foundation; either version 2, or (at your option) any later # version, or (b) the "Artistic License" which comes with this package. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See either the GNU General Public License or the # Artistic License for more details. ################################################################################ package WeBWorK::ContentGenerator::Problem; use base qw(WeBWorK::ContentGenerator); =head1 NAME WeBWorK::ContentGenerator::Problem - Allow a student to interact with a problem. =cut use strict; use warnings; use CGI qw(); use File::Path qw(rmtree); use WeBWorK::Form; use WeBWorK::PG; use WeBWorK::PG::ImageGenerator; use WeBWorK::PG::IO; use WeBWorK::Utils qw(writeLog writeCourseLog encodeAnswers decodeAnswers ref2string makeTempDirectory); use WeBWorK::DB::Utils qw(global2user user2global findDefaults); use WeBWorK::Timing; ############################################################ # # user # effectiveUser # key # # displayMode # showOldAnswers # showCorrectAnswers # showHints # showSolutions # # AnSwEr# - answer blanks in problem # # redisplay - name of the "Redisplay Problem" button # submitAnswers - name of "Submit Answers" button # checkAnswers - name of the "Check Answers" button # previewAnswers - name of the "Preview Answers" button # # FIXME: this table is heinously out of date # ############################################################ # FIXME: what is this? sub templateName { "problem"; } sub pre_header_initialize { my ($self) = @_; my $r = $self->r; my $ce = $r->ce; my $db = $r->db; my $urlpath = $r->urlpath; my $setName = $urlpath->arg("setID"); my $problemNumber = $r->urlpath->arg("problemID"); my $userName = $r->param('user'); my $effectiveUserName = $r->param('effectiveUser'); my $key = $r->param('key'); my $user = $db->getUser($userName); # checked die "record for user $userName (real user) does not exist." unless defined $user; my $effectiveUser = $db->getUser($effectiveUserName); # checked die "record for user $effectiveUserName (effective user) does not exist." unless defined $effectiveUser; my $PermissionLevel = $db->getPermissionLevel($userName); # checked die "permission level record for user $userName does not exist (but the user does? odd...)" unless defined $PermissionLevel; my $permissionLevel = $PermissionLevel->permission; # obtain the merged set for $effectiveUser my $set = $db->getMergedSet($effectiveUserName, $setName); # checked # obtain the merged problem for $effectiveUser my $problem = $db->getMergedProblem($effectiveUserName, $setName, $problemNumber); # checked my $editMode = $r->param("editMode"); if ($permissionLevel > 0 and defined $editMode) { # professors are allowed to fabricate sets and problems not # assigned to them (or anyone). this allows them to use the # editor to # if that is not yet defined obtain the global set, convert # it to a user set, and add fake user data unless (defined $set) { my $userSetClass = $db->{set_user}->{record}; my $globalSet = $db->getGlobalSet($setName); # checked # if the global set doesn't exist either, bail! die "Set $setName does not exist" unless defined $set; $set = global2user($userSetClass, $globalSet); $set->psvn(0); } # if that is not yet defined obtain the global problem, # convert it to a user problem, and add fake user data unless (defined $problem) { my $userProblemClass = $db->{problem_user}->{record}; my $globalProblem = $db->getGlobalProblem($setName, $problemNumber); # checked # if the global problem doesn't exist either, bail! die "Problem $problemNumber in set $setName does not exist" unless defined $problem; $problem = global2user($userProblemClass, $globalProblem); $problem->user_id($effectiveUserName); $problem->problem_seed(0); $problem->status(0); $problem->attempted(0); $problem->last_answer(""); $problem->num_correct(0); $problem->num_incorrect(0); } # now we're sure we have valid UserSet and UserProblem objects # yay! # now deal with possible editor overrides: # if the caller is asking to override the source file, and # editMode calls for a temporary file, do so my $sourceFilePath = $r->param("sourceFilePath"); if (defined $sourceFilePath and $editMode eq "temporaryFile") { $problem->source_file($sourceFilePath); } # if the caller is asking to override the problem seed, do so my $problemSeed = $r->param("problemSeed"); if (defined $problemSeed) { $problem->problem_seed($problemSeed); } } else { # students can't view problems not assigned to them die "Set $setName is not assigned to $effectiveUserName" unless defined $set; die "Problem $problemNumber in set $setName is not assigned to $effectiveUserName" unless defined $problem; } $self->{userName} = $userName; $self->{effectiveUserName} = $effectiveUserName; $self->{user} = $user; $self->{effectiveUser} = $effectiveUser; $self->{permissionLevel} = $permissionLevel; $self->{set} = $set; $self->{problem} = $problem; $self->{editMode} = $editMode; ##### form processing ##### # set options from form fields (see comment at top of file for names) my $displayMode = $r->param("displayMode") || $ce->{pg}->{options}->{displayMode}; my $redisplay = $r->param("redisplay"); my $submitAnswers = $r->param("submitAnswers"); my $checkAnswers = $r->param("checkAnswers"); my $previewAnswers = $r->param("previewAnswers"); my $formFields = { WeBWorK::Form->new_from_paramable($r)->Vars }; $self->{displayMode} = $displayMode; $self->{redisplay} = $redisplay; $self->{submitAnswers} = $submitAnswers; $self->{checkAnswers} = $checkAnswers; $self->{previewAnswers} = $previewAnswers; $self->{formFields} = $formFields; ##### permissions ##### # are we allowed to view this problem? $self->{isOpen} = time >= $set->open_date || $permissionLevel > 0; return unless $self->{isOpen}; # what does the user want to do? my %want = ( showOldAnswers => $r->param("showOldAnswers") || $ce->{pg}->{options}->{showOldAnswers}, showCorrectAnswers => $r->param("showCorrectAnswers") || $ce->{pg}->{options}->{showCorrectAnswers}, showHints => $r->param("showHints") || $ce->{pg}->{options}->{showHints}, showSolutions => $r->param("showSolutions") || $ce->{pg}->{options}->{showSolutions}, recordAnswers => $submitAnswers, checkAnswers => $checkAnswers, ); # are certain options enforced? my %must = ( showOldAnswers => 0, showCorrectAnswers => 0, showHints => 0, showSolutions => 0, recordAnswers => mustRecordAnswers($permissionLevel), checkAnswers => 0, ); # does the user have permission to use certain options? my %can = ( showOldAnswers => 1, showCorrectAnswers => canShowCorrectAnswers($permissionLevel, $set->answer_date), showHints => 1, showSolutions => canShowSolutions($permissionLevel, $set->answer_date), recordAnswers => canRecordAnswers($permissionLevel, $set->open_date, $set->due_date, $problem->max_attempts, $problem->num_correct + $problem->num_incorrect + 1), # attempts=num_correct+num_incorrect+1, as this happens before updating $problem checkAnswers => canCheckAnswers($permissionLevel, $set->answer_date), ); # more complicated logic for showing check answer button: # checkAnswers button shows up after due date -- once a student can't record anymore # checkAnswers button always shows up when an instructor or TA is acting # as someone else (the $user and $effectiveUserName aren't the same). $can{checkAnswers} = ( # $can{recordAnswers} will be false if the due date has passed OR the # student has used up all of her attempts ($can{checkAnswers} and not $can{recordAnswers}) or ( # FIXME: this is not the right way to check for this. # also, canCheckAnswers() will show this button if the permission # level is positive, which is always true when an instructor is # acting as a student defined($userName) and defined($effectiveUserName) and ($userName ne $effectiveUserName) ) ); # more complicated logif for showing "submit answer" button: # We hide the submit answer button if someone is acting as a student # This prevents errors where you accidently submit the answer for a student # Not sure whether this a feature or a bug $can{recordAnswers} = ( $can{recordAnswers} and not ( # FIXME: this is not the right way to check for this. defined($userName) and defined($effectiveUserName) and ($userName ne $effectiveUserName) ) ); # final values for options my %will; foreach (keys %must) { $will{$_} = $can{$_} && ($want{$_} || $must{$_}); } ##### sticky answers ##### if (not ($submitAnswers or $previewAnswers or $checkAnswers) and $will{showOldAnswers}) { # do this only if new answers are NOT being submitted my %oldAnswers = decodeAnswers($problem->last_answer); $formFields->{$_} = $oldAnswers{$_} foreach keys %oldAnswers; } ##### translation ##### $WeBWorK::timer->continue("begin pg processing") if defined($WeBWorK::timer); my $pg = WeBWorK::PG->new( $ce, $effectiveUser, $key, $set, $problem, $set->psvn, # FIXME: this field should be removed $formFields, { # translation options displayMode => $displayMode, showHints => $will{showHints}, showSolutions => $will{showSolutions}, refreshMath2img => $will{showHints} || $will{showSolutions}, processAnswers => 1, }, ); $WeBWorK::timer->continue("end pg processing") if defined($WeBWorK::timer); ##### fix hint/solution options ##### $can{showHints} &&= $pg->{flags}->{hintExists} &&= $pg->{flags}->{showHintLimit}<=$pg->{state}->{num_of_incorrect_ans}; $can{showSolutions} &&= $pg->{flags}->{solutionExists}; ##### store fields ##### $self->{want} = \%want; $self->{must} = \%must; $self->{can} = \%can; $self->{will} = \%will; $self->{pg} = $pg; } sub if_errors($$) { my ($self, $arg) = @_; if ($self->{isOpen}) { return $self->{pg}->{flags}->{error_flag} ? $arg : !$arg; } else { return !$arg; } } sub head { my ($self) = @_; return "" unless $self->{isOpen}; return $self->{pg}->{head_text} if $self->{pg}->{head_text}; } sub options { my ($self) = @_; return join("", CGI::start_form("POST", $self->{r}->uri), $self->hidden_authen_fields, CGI::hr(), CGI::start_div({class=>"viewOptions"}), $self->viewOptions(), CGI::end_div(), CGI::end_form() ); } #sub path { # my $self = shift; # my $args = $_[-1]; # my $setName = $self->{set}->set_id; # my $problemNumber = $self->{problem}->problem_id; # # my $ce = $self->{ce}; # my $root = $ce->{webworkURLs}->{root}; # my $courseName = $ce->{courseName}; # return $self->pathMacro($args, # "Home" => "$root", # $courseName => "$root/$courseName", # $setName => "$root/$courseName/$setName", # "Problem $problemNumber" => "", # ); #} sub siblings { my ($self) = @_; my $r = $self->r; my $db = $r->db; my $urlpath = $r->urlpath; my $courseID = $urlpath->arg("courseID"); my $setID = $self->{set}->set_id; my $eUserID = $r->param("effectiveUser"); my @problemIDs = sort { $a <=> $b } $db->listUserProblems($eUserID, $setID); print CGI::start_ul({class=>"LinksMenu"}); print CGI::start_li(); print CGI::span({style=>"font-size:larger"}, "Problems"); print CGI::start_ul(); foreach my $problemID (@problemIDs) { my $problemPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Problem", courseID => $courseID, setID => $setID, problemID => $problemID); print CGI::li(CGI::a({href=>$self->systemLink($problemPage)}, "Problem $problemID")); } print CGI::end_ul(); print CGI::end_li(); print CGI::end_ul(); return ""; } sub nav { my ($self, $args) = @_; my $r = $self->r; my $db = $r->db; my $urlpath = $r->urlpath; my $courseID = $urlpath->arg("courseID"); my $setID = $self->{set}->set_id; my $problemID = $self->{problem}->problem_id; my $eUserID = $r->param("effectiveUser"); my ($prevID, $nextID); my @problemIDs = $db->listUserProblems($eUserID, $setID); foreach my $id (@problemIDs) { $prevID = $id if $id < $problemID and (not defined $prevID or $id > $prevID); $nextID = $id if $id > $problemID and (not defined $nextID or $id < $nextID); } my @links; if ($prevID) { my $prevPage = $urlpath->newFromModule(__PACKAGE__, courseID => $courseID, setID => $setID, problemID => $prevID); push @links, "Previous Problem", $r->location . $prevPage->path, "navPrev"; } else { push @links, "Previous Problem", "", "navPrev"; } push @links, "Problem List", $r->location . $urlpath->parent->path, "navProbList"; if ($nextID) { my $nextPage = $urlpath->newFromModule(__PACKAGE__, courseID => $courseID, setID => $setID, problemID => $nextID); push @links, "Next Problem", $r->location . $nextPage->path, "navNext"; } else { push @links, "Next Problem", "", "navNext"; } my $tail = "&displayMode=".$self->{displayMode}; return $self->navMacro($args, $tail, @links); } sub title { my ($self) = @_; my $setID = $self->{set}->set_id; my $problemID = $self->{problem}->problem_id; return "$setID : $problemID"; } sub body { my $self = shift; my $r = $self->r; my $ce = $r->ce; my $db = $r->db; my $urlpath = $r->urlpath; unless ($self->{isOpen}) { return CGI::div({class=>"ResultsWithError"}, CGI::p("This problem is not available because the problem set that contains it is not yet open.")); } # unpack some useful variables my $set = $self->{set}; my $problem = $self->{problem}; my $editMode = $self->{editMode}; my $permissionLevel = $self->{permissionLevel}; my $submitAnswers = $self->{submitAnswers}; my $checkAnswers = $self->{checkAnswers}; my $previewAnswers = $self->{previewAnswers}; my %want = %{ $self->{want} }; my %can = %{ $self->{can} }; my %must = %{ $self->{must} }; my %will = %{ $self->{will} }; my $pg = $self->{pg}; #my $root = $ce->{webworkURLs}->{root}; my $courseName = $urlpath->arg("courseID"); #####create Editor link ##### ## print editor link if the user is an instructor AND the file is not in temporary editing mode #my $editorLinkMessage = ''; ## and ( (not defined($self->{editMode})) or $self->{editMode} eq 'savedFile') # FIXME is this needed? #if ($self->{permissionLevel}>=10 ) { # $editorLinkMessage = CGI::a({-href=>$ce->{webworkURLs}->{root}."/$courseName/instructor/pgProblemEditor/". # $set->set_id.'/'.$problem->problem_id.'?'.$self->url_authen_args},'Edit this problem'); #} my $editorLink = ""; if ($self->{permissionLevel}>=10) { my $editorPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::PGProblemEditor", courseID => $courseName, setID => $set->set_id, problemID => $problem->problem_id); my $editorURL = $self->systemLink($editorPage); $editorLink = CGI::a({href=>$editorURL}, "Edit this problem"); } ##### translation errors? ##### if ($pg->{flags}->{error_flag}) { print $self->errorOutput($pg->{errors}, $pg->{body_text}); print $editorLink; return ""; } ##### answer processing ##### $WeBWorK::timer->continue("begin answer processing") if defined($WeBWorK::timer); # if answers were submitted: my $scoreRecordedMessage; if ($submitAnswers) { # get a "pure" (unmerged) UserProblem to modify # this will be undefined if the problem has not been assigned to this user my $pureProblem = $db->getUserProblem($problem->user_id, $problem->set_id, $problem->problem_id); # checked if (defined $pureProblem) { # store answers in DB for sticky answers my %answersToStore; my %answerHash = %{ $pg->{answers} }; $answersToStore{$_} = $self->{formFields}->{$_} #$answerHash{$_}->{original_student_ans} -- this may have been modified for fields with multiple values. Don't use it!! foreach (keys %answerHash); # There may be some more answers to store -- one which are auxiliary entries to a primary answer. Evaluating # matrices works in this way, only the first answer triggers an answer evaluator, the rest are just inputs # however we need to store them. Fortunately they are still in the input form. my @extra_answer_names = @{ $pg->{flags}->{KEPT_EXTRA_ANSWERS}}; $answersToStore{$_} = $self->{formFields}->{$_} foreach (@extra_answer_names); # Now let's encode these answers to store them -- append the extra answers to the end of answer entry order my @answer_order = (@{$pg->{flags}->{ANSWER_ENTRY_ORDER}}, @extra_answer_names); my $answerString = encodeAnswers(%answersToStore, @answer_order); # store last answer to database $problem->last_answer($answerString); $pureProblem->last_answer($answerString); $db->putUserProblem($pureProblem); # store state in DB if it makes sense if ($will{recordAnswers}) { $problem->status($pg->{state}->{recorded_score}); $problem->attempted(1); $problem->num_correct($pg->{state}->{num_of_correct_ans}); $problem->num_incorrect($pg->{state}->{num_of_incorrect_ans}); $pureProblem->status($pg->{state}->{recorded_score}); $pureProblem->attempted(1); $pureProblem->num_correct($pg->{state}->{num_of_correct_ans}); $pureProblem->num_incorrect($pg->{state}->{num_of_incorrect_ans}); if ($db->putUserProblem($pureProblem)) { $scoreRecordedMessage = "Your score was recorded."; } else { $scoreRecordedMessage = "Your score was not recorded because there was a failure in storing the problem record to the database."; } # write to the transaction log, just to make sure writeLog($self->{ce}, "transaction", $problem->problem_id."\t". $problem->set_id."\t". $problem->user_id."\t". $problem->source_file."\t". $problem->value."\t". $problem->max_attempts."\t". $problem->problem_seed."\t". $pureProblem->status."\t". $pureProblem->attempted."\t". $pureProblem->last_answer."\t". $pureProblem->num_correct."\t". $pureProblem->num_incorrect ); } else { if (time < $set->open_date or time > $set->due_date) { $scoreRecordedMessage = "Your score was not recorded because this problem set is closed."; } else { $scoreRecordedMessage = "Your score was not recorded."; } } } else { $scoreRecordedMessage = "Your score was not recorded because this problem has not been built for you."; } } # logging student answers my $answer_log = $self->{ce}->{courseFiles}->{logs}->{'answer_log'}; if ( defined($answer_log )) { if ($submitAnswers ) { my $answerString = ""; my %answerHash = %{ $pg->{answers} }; # FIXME this is the line 552 error. make sure original student ans is defined. # The fact that it is not defined is probably due to an error in some answer evaluator. # But I think it is useful to suppress this error message in the log. foreach (sort keys %answerHash) { my $student_ans = $answerHash{$_}->{original_student_ans} ||''; $answerString .= $student_ans."\t" } $answerString = '' unless defined($answerString); # insure string is defined. writeCourseLog($self->{ce}, "answer_log", join("", '|', $problem->user_id, '|', $problem->set_id, '|', $problem->problem_id, '|',"\t", time(),"\t", $answerString, ), ); } } $WeBWorK::timer->continue("end answer processing") if defined($WeBWorK::timer); ##### output ##### print CGI::start_div({class=>"problemHeader"}); # custom message for editor if ($permissionLevel >= 10 and defined $editMode) { if ($editMode eq "temporaryFile") { print CGI::p(CGI::i("Editing temporary file: ", $problem->source_file)); } elsif ($editMode eq "savedFile") { if ( defined($r->param('submiterror')) and $r->param('submiterror') ) { # FIXME The following line doesn't work because the submiterror hook has already been called. # The actions below should take place during the initialization phase. $self->{submiterror} .= $r->param('submiterror'); print CGI::p(CGI::div({class=>'ResultsWithError'},$self->{submiterror})); } else { print CGI::p(CGI::div({ class=>'ResultsWithoutError'}, "Problem saved to: ", $problem->source_file)); } } } #FIXME we need error messages here if the problem was really not saved. # attempt summary #FIXME -- the following is a kludge: if showPartialCorrectAnswers is negative don't show anything. # until after the due date # do I need to check $wills{howCorrectAnswers} to make preflight work?? if (($pg->{flags}->{showPartialCorrectAnswers}>= 0 and $submitAnswers) ) { # print this if user submitted answers OR requested correct answers print $self->attemptResults($pg, 1, $will{showCorrectAnswers}, $pg->{flags}->{showPartialCorrectAnswers}, 1, 1); } elsif ($checkAnswers) { # print this if user previewed answers print "ANSWERS ONLY CHECKED -- ",CGI::br(),"ANSWERS NOT RECORDED", CGI::br(); print $self->attemptResults($pg, 1, $will{showCorrectAnswers}, 1, 1, 1); # show attempt answers # show correct answers if asked # show attempt results (correctness) # show attempt previews } elsif ($previewAnswers) { # print this if user previewed answers print "PREVIEW ONLY -- NOT RECORDED",CGI::br(),$self->attemptResults($pg, 1, 0, 0, 0, 1); # show attempt answers # don't show correct answers # don't show attempt results (correctness) # show attempt previews } print CGI::end_div(); print CGI::start_div({class=>"problem"}); # main form print CGI::startform("POST", $r->uri), $self->hidden_authen_fields, CGI::p($pg->{body_text}), CGI::p($pg->{result}->{msg} ? CGI::b("Note: ") : "", CGI::i($pg->{result}->{msg})), CGI::p( ($can{showCorrectAnswers} ? CGI::checkbox( -name => "showCorrectAnswers", -checked => $will{showCorrectAnswers}, -label => "Show correct answers", ) ." " : "" ), ($can{showHints} ? '