--- trunk/webwork-modperl/lib/WeBWorK/ContentGenerator/Problem.pm 2003/06/20 00:36:47 1223 +++ trunk/webwork-modperl/lib/WeBWorK/ContentGenerator/Problem.pm 2003/09/23 21:09:24 1514 @@ -18,8 +18,9 @@ use File::Path qw(rmtree); use WeBWorK::Form; use WeBWorK::PG; +use WeBWorK::PG::ImageGenerator; use WeBWorK::PG::IO; -use WeBWorK::Utils qw(writeLog encodeAnswers decodeAnswers ref2string makeTempDirectory); +use WeBWorK::Utils qw(writeLog writeCourseLog encodeAnswers decodeAnswers ref2string makeTempDirectory); use WeBWorK::DB::Utils qw(global2user user2global findDefaults); use WeBWorK::Timing; @@ -44,6 +45,10 @@ # ############################################################ +sub templateName { + "problem"; +} + sub pre_header_initialize { my ($self, $setName, $problemNumber) = @_; my $r = $self->{r}; @@ -206,7 +211,28 @@ # 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{checkAnswers} && not $can{recordAnswers} ) || + ( 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 + ( defined($userName) and defined($effectiveUserName) and + ($userName ne $effectiveUserName) + ) + ); # final values for options my %will; foreach (keys %must) { @@ -215,7 +241,7 @@ ##### sticky answers ##### - if (not $submitAnswers and $will{showOldAnswers}) { + 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; @@ -319,7 +345,7 @@ my $effectiveUser = $self->{r}->param("effectiveUser"); my @problemIDs = $db->listUserProblems($effectiveUser, $setName); foreach my $problem (sort { $a <=> $b } @problemIDs) { - print CGI::a({-href=>"$root/$courseName/$setName/".$problem."/?" + print '  '.CGI::a({-href=>"$root/$courseName/$setName/".$problem."/?" . $self->url_authen_args . "&displayMode=" . $self->{displayMode}}, "Problem ".$problem), CGI::br(); } @@ -404,29 +430,34 @@ ##### answer processing ##### $WeBWorK::timer0->continue("begin answer processing") if $timer0_ON; # 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); - # store answers in DB for sticky answers - my %answersToStore; - my %answerHash = %{ $pg->{answers} }; - $answersToStore{$_} = $answerHash{$_}->{original_student_ans} - foreach (keys %answerHash); - my $answerString = encodeAnswers(%answersToStore, - @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} }); - - $problem->last_answer($answerString); - # if $pureProblem is defined ( there is a user ) then record the last answer. - # FIXME (we're assuming that not being able to get a pure problem is enough to determine - # whether or not the problem database needs to be updated. This should be thought through - # more carefully to be sure. - if ( defined($pureProblem) ) { + if (defined $pureProblem) { + # store answers in DB for sticky answers + my %answersToStore; + my %answerHash = %{ $pg->{answers} }; + $answersToStore{$_} = $answerHash{$_}->{original_student_ans} + 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{$_} = $r->param($_) 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); - #die "pureProblem = ", defined($pureProblem); - - + # store state in DB if it makes sense if ($will{recordAnswers}) { $problem->status($pg->{state}->{recorded_score}); @@ -437,7 +468,11 @@ $pureProblem->attempted(1); $pureProblem->num_correct($pg->{state}->{num_of_correct_ans}); $pureProblem->num_incorrect($pg->{state}->{num_of_incorrect_ans}); - $db->putUserProblem($pureProblem); + 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". @@ -453,29 +488,41 @@ $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 $pastAnswerLog = undef; - if (defined( $self->{ce}->{webworkFiles}->{logs}->{'pastAnswerList'} )) { - $pastAnswerLog = $self->{ce}->{webworkFiles}->{logs}->{'pastAnswerList'}; - if ($submitAnswers and defined $pastAnswerLog) { + + my $answer_log = $self->{ce}->{courseFiles}->{logs}->{'answer_log'}; + if ( defined($answer_log )) { + if ($submitAnswers ) { my $answerString = ""; my %answerHash = %{ $pg->{answers} }; $answerString = $answerString . $answerHash{$_}->{original_student_ans}."\t" foreach (sort keys %answerHash); $answerString = '' unless defined($answerString); # insure string is defined. - writeLog($self->{ce}, "pastAnswerList", - '|'.$problem->user_id. - '|'.$problem->set_id. - '|'.$problem->problem_id.'|'."\t". - time()."\t". - $answerString, - ); + writeCourseLog($self->{ce}, "answer_log", + join("", + '|', $problem->user_id, + '|', $problem->set_id, + '|', $problem->problem_id, + '|',"\t", + time(),"\t", + $answerString, + ), + ); + } } - # end logging student answers $WeBWorK::timer0->continue("end answer processing") if $timer0_ON; @@ -493,21 +540,26 @@ } # attempt summary - if ($submitAnswers or $will{showCorrectAnswers}) { + #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, $submitAnswers, + + print $self->attemptResults($pg, 1, $will{showCorrectAnswers}, $pg->{flags}->{showPartialCorrectAnswers}, 1, 1); } elsif ($checkAnswers) { # print this if user previewed answers - print $self->attemptResults($pg, 1, 0, 1, 1, 1); + print "ANSWERS ONLY CHECKED -- ",CGI::br(),"ANSWERS NOT RECORDED", CGI::br(); + print $self->attemptResults($pg, 1, $will{showCorrectAnswers}, 1, 1, 1); # show attempt answers - # don't show correct answers + # show correct answers if asked # show attempt results (correctness) - # don't show attempt previews + # show attempt previews } elsif ($previewAnswers) { # print this if user previewed answers - print $self->attemptResults($pg, 1, 0, 0, 0, 1); + 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) @@ -525,16 +577,37 @@ 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} + ? CGI::checkbox( + -name => "showHints", + -checked => $will{showHints}, + -label => "Show Hints", + ) . " " + : " " ), + ($can{showSolutions} + ? CGI::checkbox( + -name => "showSolutions", + -checked => $will{showSolutions}, + -label => "Show Solutions", + ) . " " + : " " ),CGI::br(), + CGI::submit(-name=>"previewAnswers", + -label=>"Preview Answers"), ($can{recordAnswers} ? CGI::submit(-name=>"submitAnswers", -label=>"Submit Answers") : ""), - ($can{checkAnswers} + ( $can{checkAnswers} ? CGI::submit(-name=>"checkAnswers", -label=>"Check Answers") : ""), - CGI::submit(-name=>"previewAnswers", - -label=>"Preview Answers"), ); print CGI::end_div(); @@ -566,6 +639,7 @@ } } print CGI::p( + $submitAnswers ? $scoreRecordedMessage . CGI::br() : "", "You have attempted this problem $attempts $attemptsNoun.", CGI::br(), $problem->attempted ? "Your recorded score is $lastScore." . CGI::br() @@ -579,17 +653,7 @@ -name => "showOldAnswers", -value => $will{showOldAnswers} ), - CGI::hidden( - -name => "showCorrectAnswers", - -value => $will{showCorrectAnswers} - ), - CGI::hidden( - -name => "showHints", - -value => $will{showHints}), - CGI::hidden( - -name => "showSolutions", - -value => $will{showSolutions}, - ), + CGI::hidden( -name => "displayMode", -value => $self->{displayMode} @@ -607,10 +671,11 @@ # arguments for answer inspection button my $prof_url = $ce->{webworkURLs}->{oldProf}; + my $webworkURL = $ce->{webworkURLs}->{root}; my $cgi_url = $prof_url; $cgi_url=~ s|/[^/]*$||; # clip profLogin.pl my $authen_args = $self->url_authen_args(); - my $showPastAnswersURL = "$cgi_url/showPastAnswers.pl"; + my $showPastAnswersURL = "$webworkURL/$courseName/instructor/show_answers/"; # print answer inspection button if ($self->{permissionLevel} > 0) { @@ -618,9 +683,9 @@ CGI::start_form(-method=>"POST",-action=>$showPastAnswersURL,-target=>"information"),"\n", $self->hidden_authen_fields,"\n", CGI::hidden(-name => 'course', -value=>$courseName), "\n", - CGI::hidden(-name => 'probNum', -value=>$problem->problem_id), "\n", - CGI::hidden(-name => 'setNum', -value=>$problem->set_id), "\n", - CGI::hidden(-name => 'User', -value=>$problem->user_id), "\n", + CGI::hidden(-name => 'problemNumber', -value=>$problem->problem_id), "\n", + CGI::hidden(-name => 'setName', -value=>$problem->set_id), "\n", + CGI::hidden(-name => 'studentUser', -value=>$problem->user_id), "\n", CGI::p( {-align=>"left"}, CGI::submit(-name => 'action', -value=>'Show Past Answers') ), "\n", @@ -647,7 +712,7 @@ CGI::hidden("showHints", $will{showHints}),"\n", CGI::hidden("showSolutions", $will{showSolutions}),"\n", CGI::p({-align=>"left"}, - CGI::submit(-name=>"feedbackForm", -label=>"Contact instructor") + CGI::submit(-name=>"feedbackForm", -label=>"Email instructor") ), CGI::endform(),"\n"; @@ -695,12 +760,28 @@ my $showAttemptResults = $showAttemptAnswers && shift; my $showSummary = shift; my $showAttemptPreview = shift || 0; + my $ce = $self->{ce}; my $problemResult = $pg->{result}; # the overall result of the problem my @answerNames = @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} }; my $showMessages = $showAttemptAnswers && grep { $pg->{answers}->{$_}->{ans_message} } @answerNames; - my $header = CGI::th("Part"); + my $basename = "equation-" . $self->{set}->psvn. "." . $self->{problem}->problem_id . "-preview"; + my $imgGen = WeBWorK::PG::ImageGenerator->new( + tempDir => $ce->{webworkDirs}->{tmp}, + dir => $ce->{courseDirs}->{html_temp}, + url => $ce->{courseURLs}->{html_temp}, + basename => $basename, + latex => $ce->{externalPrograms}->{latex}, + dvipng => $ce->{externalPrograms}->{dvipng}, + useCache => 1, + cacheDir => $ce->{webworkDirs}->{equationCache}, + cacheURL => $ce->{webworkURLs}->{equationCache}, + cacheDB => $ce->{webworkFiles}->{equationCacheDB}, + ); + + my $header; + #$header .= CGI::th("Part"); $header .= $showAttemptAnswers ? CGI::th("Entered") : ""; $header .= $showAttemptPreview ? CGI::th("Answer Preview") : ""; $header .= $showCorrectAnswers ? CGI::th("Correct") : ""; @@ -712,20 +793,21 @@ my $answerResult = $pg->{answers}->{$name}; my $studentAnswer = $answerResult->{student_ans}; # original_student_ans my $preview = ($showAttemptPreview - ? $self->previewAnswer($answerResult) - : ""); + ? $self->previewAnswer($answerResult, $imgGen) + : ""); my $correctAnswer = $answerResult->{correct_ans}; my $answerScore = $answerResult->{score}; my $answerMessage = $showMessages ? $answerResult->{ans_message} : ""; - + #FIXME --Can we be sure that $answerScore is an integer-- could the problem give partial credit? $numCorrect += $answerScore > 0; my $resultString = $answerScore ? "correct" : "incorrect"; # get rid of the goofy prefix on the answer names (supposedly, the format # of the answer names is changeable. this only fixes it for "AnSwEr" - $name =~ s/^AnSwEr//; + #$name =~ s/^AnSwEr//; - my $row = CGI::td($name); + my $row; + #$row .= CGI::td($name); $row .= $showAttemptAnswers ? CGI::td(nbsp($studentAnswer)) : ""; $row .= $showAttemptPreview ? CGI::td(nbsp($preview)) : ""; $row .= $showCorrectAnswers ? CGI::td(nbsp($correctAnswer)) : ""; @@ -734,15 +816,39 @@ push @tableRows, $row; } - my $numIncorrectNoun = scalar @answerNames == 1 ? "question" : "questions"; + # render equation images + $imgGen->render(refresh => 1); + +# my $numIncorrectNoun = scalar @answerNames == 1 ? "question" : "questions"; my $scorePercent = sprintf("%.0f%%", $problemResult->{score} * 100); - my $summary = "On this attempt, you answered $numCorrect out of " - . scalar @answerNames . " $numIncorrectNoun correct, for a score of $scorePercent."; - return CGI::table({-class=>"attemptResults"}, CGI::Tr(\@tableRows)) . ($showSummary ? CGI::p($summary) : ""); +# FIXME -- I left the old code in in case we have to back out. +# my $summary = "On this attempt, you answered $numCorrect out of " +# . scalar @answerNames . " $numIncorrectNoun correct, for a score of $scorePercent."; + my $summary = ""; + if (scalar @answerNames == 1) { + if ($numCorrect == scalar @answerNames) { + $summary .= "The above answer is correct."; + } else { + $summary .= "The above answer is NOT correct."; + } + } else { + if ($numCorrect == scalar @answerNames) { + $summary .= "All of the above answers are correct."; + } else { + $summary .= "At least one of the above answers is NOT correct."; + } + } + #FIXME there must be a better way to force refresh. + my $refresh_warning = 'Hold down shift and click "refresh" or "reload" to update answer preview images.'; + return CGI::table({-class=>"attemptResults"}, CGI::Tr(\@tableRows)) . + CGI::div({style=>'color:red; font-size:10pt'},$refresh_warning) . + ($showSummary ? CGI::p({class=>'emphasis'},$summary) : ""); } sub nbsp { my $str = shift; - ($str) ? $str : ' '; # returns non-breaking space for empty strings + ($str =~/\S/) ? $str : ' ' ; # returns non-breaking space for empty strings + # tricky cases: $str =0; + # $str is a complex number } sub viewOptions($) { my $self = shift; @@ -759,24 +865,7 @@ -checked => $will{showOldAnswers}, -label => "Saved answers", ), "  ".CGI::br(); - $can{showCorrectAnswers} and $optionLine .= join "", - CGI::checkbox( - -name => "showCorrectAnswers", - -checked => $will{showCorrectAnswers}, - -label => "Correct answers", - ), "  ".CGI::br(); - $can{showHints} and $optionLine .= join "", - CGI::checkbox( - -name => "showHints", - -checked => $will{showHints}, - -label => "Hints", - ), "  ".CGI::br(); - $can{showSolutions} and $optionLine .= join "", - CGI::checkbox( - -name => "showSolutions", - -checked => $will{showSolutions}, - -label => "Solutions", - ), "  ".CGI::br(); + $optionLine and $optionLine .= join "", CGI::br(); return CGI::div({-style=>"border: thin groove; padding: 1ex; margin: 2ex align: left"}, @@ -798,7 +887,7 @@ } sub previewAnswer($$) { - my ($self, $answerResult) = @_; + my ($self, $answerResult, $imgGen) = @_; my $ce = $self->{ce}; my $effectiveUser = $self->{effectiveUser}; my $set = $self->{set}; @@ -812,7 +901,7 @@ my $tex = $answerResult->{preview_latex_string}; - return "" if $tex eq ""; + return "" unless defined $tex and $tex ne ""; if ($displayMode eq "plainText") { return $tex; @@ -829,30 +918,32 @@ } return $result; } elsif ($displayMode eq "images") { - # how are we going to name this? - my $targetPathCommon = "/m2i/" - . $effectiveUser->user_id . "." - . $set->set_id . "." - . $problem->problem_id . "." - . $answerResult->{ans_name} . ".png"; - - # figure out where to put things - my $wd = makeTempDirectory($ce->{courseDirs}->{html_temp}, "webwork-dvipng"); - my $latex = $ce->{externalPrograms}->{latex}; - my $dvipng = $ce->{externalPrograms}->{dvipng}; - my $targetPath = $ce->{courseDirs}->{html_temp} . $targetPathCommon; - # should use surePathToTmpFile, but we have to - # isolate it from the problem enivronment first - my $targetURL = $ce->{courseURLs}->{html_temp} . $targetPathCommon; - - # call dvipng to generate a preview - dvipng($wd, $latex, $dvipng, $tex, $targetPath); - rmtree($wd, 0, 0); - if (-e $targetPath) { - return "\"$tex\""; - } else { - return "[math2img failed]"; - } + ## how are we going to name this? + #my $targetPathCommon = "/m2i/" + # . $effectiveUser->user_id . "." + # . $set->set_id . "." + # . $problem->problem_id . "." + # . $answerResult->{ans_name} . ".png"; + # + ## figure out where to put things + #my $wd = makeTempDirectory($ce->{courseDirs}->{html_temp}, "webwork-dvipng"); + #my $latex = $ce->{externalPrograms}->{latex}; + #my $dvipng = $ce->{externalPrograms}->{dvipng}; + #my $targetPath = $ce->{courseDirs}->{html_temp} . $targetPathCommon; + # # should use surePathToTmpFile, but we have to + # # isolate it from the problem enivronment first + #my $targetURL = $ce->{courseURLs}->{html_temp} . $targetPathCommon; + # + ## call dvipng to generate a preview + #dvipng($wd, $latex, $dvipng, $tex, $targetPath); + #rmtree($wd, 0, 0); + #if (-e $targetPath) { + # return "\"$tex\""; + #} else { + # return "[math2img failed]"; + #} + $imgGen->add($answerResult->{preview_latex_string}); + } }