--- trunk/webwork2/lib/WeBWorK/ContentGenerator/Problem.pm 2003/09/25 02:03:43 1530 +++ trunk/webwork2/lib/WeBWorK/ContentGenerator/Problem.pm 2004/07/03 17:29:32 2440 @@ -1,6 +1,17 @@ ################################################################################ -# WeBWorK mod_perl (c) 2000-2002 WeBWorK Project -# $Id$ +# 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.150 2004/07/02 20:39:12 dpvc 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; @@ -11,7 +22,7 @@ WeBWorK::ContentGenerator::Problem - Allow a student to interact with a problem. =cut -my $timer0_ON=0; # times pg translation phase + use strict; use warnings; use CGI qw(); @@ -24,13 +35,20 @@ use WeBWorK::DB::Utils qw(global2user user2global findDefaults); use WeBWorK::Timing; +use WeBWorK::Utils::Tasks qw(fake_set fake_problem); + ############################################################ # # user # effectiveUser # key # -# displayMode +# editMode +# sourceFilePath - path to file to be editted +# problemSeed - problem seed for editted problem +# +# displayMode - type of display (ie formatted, images, asciimath, etc) +# # showOldAnswers # showCorrectAnswers # showHints @@ -43,33 +61,48 @@ # checkAnswers - name of the "Check Answers" button # previewAnswers - name of the "Preview Answers" button # +# success - success message (from PGProblemEditor) +# failure - failure message (from PGProblemEditor) +# ############################################################ -sub templateName { - "problem"; -} sub pre_header_initialize { - my ($self, $setName, $problemNumber) = @_; - my $r = $self->{r}; - my $courseEnv = $self->{ce}; - my $db = $self->{db}; - my $userName = $r->param('user'); - my $effectiveUserName = $r->param('effectiveUser'); - my $key = $r->param('key'); - my $user = $db->getUser($userName); - my $effectiveUser = $db->getUser($effectiveUserName); - my $permissionLevel = $db->getPermissionLevel($userName)->permission(); + my ($self) = @_; + my $r = $self->r; + my $ce = $r->ce; + my $db = $r->db; + my $authz = $r->authz; + 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); + my $set = $db->getMergedSet($effectiveUserName, $setName); # checked # obtain the merged problem for $effectiveUser - my $problem = $db->getMergedProblem($effectiveUserName, $setName, $problemNumber); - + my $problem = $db->getMergedProblem($effectiveUserName, $setName, $problemNumber); # checked + my $editMode = $r->param("editMode"); - if ($permissionLevel > 0 and defined $editMode) { + if ($authz->hasPermissions($userName, "modify_problem_sets")) { # professors are allowed to fabricate sets and problems not # assigned to them (or anyone). this allows them to use the # editor to @@ -78,28 +111,47 @@ # it to a user set, and add fake user data unless (defined $set) { my $userSetClass = $db->{set_user}->{record}; - $set = global2user($userSetClass, - $db->getGlobalSet($setName)); - die "Set $setName does not exist" - unless defined $set; - $set->psvn(0); + my $globalSet = $db->getGlobalSet($setName); # checked + # if the global set doesn't exist either, bail! + if(not defined $globalSet) { + $set = fake_set($db); + } else { + $set = global2user($userSetClass, $globalSet); + $set->psvn(0); + + # FIXME: This is a temporary fix to fill in the database + # We want the published field to contain either 1 or 0 so if it has not been set to 0, default to 1 + # this will fill in all the empty fields but not change anything that has been specifically set to 1 or 0 + $globalSet->published("1") unless $globalSet->published eq "0"; + $db->putGlobalSet($globalSet); + } } # 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}; - $problem = global2user($userProblemClass, - $db->getGlobalProblem($setName,$problemNumber)); - die "Problem $problemNumber in set $setName does not exist" - unless defined $problem; - $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); + my $globalProblem = $db->getGlobalProblem($setName, $problemNumber); # checked + # if the global problem doesn't exist either, bail! + if(not defined $globalProblem) { + my $sourceFilePath = $r->param("sourceFilePath"); + # These are problems from setmaker. If declared invalid, they won't come up + $self->{invalidProblem} = $self->{invalidSet} = 1 unless defined $sourceFilePath; +# die "Problem $problemNumber in set $setName does not exist" unless defined $sourceFilePath; + $problem = fake_problem($db); + $problem->problem_id(1); + $problem->source_file($sourceFilePath); + $problem->user_id($effectiveUserName); + } else { + $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 @@ -110,23 +162,39 @@ # 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") { + if (defined $sourceFilePath and + (not defined $editMode or $editMode eq "temporaryFile")) { $problem->source_file($sourceFilePath); } + # if the problem does not have a source file or no source file has been passed in + # then this is really an invalid problem (probably from a bad URL) + $self->{invalidProblem} = not (defined $sourceFilePath or $problem->source_file); + # if the caller is asking to override the problem seed, do so my $problemSeed = $r->param("problemSeed"); if (defined $problemSeed) { $problem->problem_seed($problemSeed); } + + my $publishedClass = ($set->published) ? "Published" : "Unpublished"; + my $publishedText = ($set->published) ? "visible to students." : "hidden from students."; + $self->addmessage(CGI::p("This set is " . CGI::font({class=>$publishedClass}, $publishedText))); } 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; + + # A set is valid if it exists and if it is either published or the user is privileged. + $self->{invalidSet} = ((grep /^$setName/, $db->listUserSets($effectiveUserName)) == 0) + || not defined $set + || !($set->published || $authz->hasPermissions($userName, "view_unpublished_sets")); + $self->{invalidProblem} = ((grep /^$problemNumber/, $db->listUserProblems($effectiveUserName, $setName)) == 0) + || not defined $problem + || !($set->published || $authz->hasPermissions($userName, "view_unpublished_sets")); + + $self->addbadmessage(CGI::p("This problem will not count towards your grade.")) if $problem and not $problem->value and not $self->{invalidProblem}; } - + $self->{userName} = $userName; $self->{effectiveUserName} = $effectiveUserName; $self->{user} = $user; @@ -139,32 +207,12 @@ ##### form processing ##### # set options from form fields (see comment at top of file for names) - my $displayMode = $r->param("displayMode") || $courseEnv->{pg}->{options}->{displayMode}; + 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"); - # fields which may be defined when using Problem Editor - #my $override_seed = ($permissionLevel>=10) ? $r->param('problemSeed') : undef; - #my $override_problem_source = ($permissionLevel>=10) ? $r->param('sourceFilePath') : undef; - #my $editMode = undef; - #my $submit_button = $r->param('submit_button'); - #if ( defined($submit_button ) ) { - # $editMode = "temporaryFile" if $submit_button eq 'Refresh'; - # $editMode = 'savedFile' if $submit_button eq 'Save'; - #} - # - ##override using the source file data from the form field - #$problem->source_file($override_problem_source) if defined($override_problem_source); - #$problem->problem_seed($override_seed) if defined($override_seed); - # - ## store path to source file for title. - #$self->{problem_source_name} = $problem->source_file; - #$self->{edit_mode} = $editMode; - #$self->{current_problem_source} = (defined($override_problem_source) ) ? - - # coerce form fields into CGI::Vars format my $formFields = { WeBWorK::Form->new_from_paramable($r)->Vars }; $self->{displayMode} = $displayMode; @@ -173,19 +221,28 @@ $self->{checkAnswers} = $checkAnswers; $self->{previewAnswers} = $previewAnswers; $self->{formFields} = $formFields; + + # get result and send to message + my $success = $r->param("sucess"); + my $failure = $r->param("failure"); + $self->addbadmessage(CGI::p($failure)) if $failure; + $self->addgoodmessage(CGI::p($success)) if $success; + + # now that we've set all the necessary variables quit out if the set or problem is invalid + return if $self->{invalidSet} || $self->{invalidProblem}; ##### permissions ##### # are we allowed to view this problem? - $self->{isOpen} = time >= $set->open_date || $permissionLevel > 0; + $self->{isOpen} = time >= $set->open_date || $authz->hasPermissions($user, "view_unopened_sets"); return unless $self->{isOpen}; # what does the user want to do? my %want = ( - showOldAnswers => $r->param("showOldAnswers") || $courseEnv->{pg}->{options}->{showOldAnswers}, - showCorrectAnswers => $r->param("showCorrectAnswers") || $courseEnv->{pg}->{options}->{showCorrectAnswers}, - showHints => $r->param("showHints") || $courseEnv->{pg}->{options}->{showHints}, - showSolutions => $r->param("showSolutions") || $courseEnv->{pg}->{options}->{showSolutions}, + 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, ); @@ -209,30 +266,48 @@ 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), + checkAnswers => canCheckAnswers($permissionLevel, $set->due_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 - ######################################################### + $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 logic 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) + ) + ); - $can{recordAnswers} = ($can{recordAnswers} and not - ( defined($userName) and defined($effectiveUserName) and - ($userName ne $effectiveUserName) - ) - ); # final values for options my %will; foreach (keys %must) { @@ -249,9 +324,9 @@ ##### translation ##### - $WeBWorK::timer0->continue("begin pg processing") if $timer0_ON; + $WeBWorK::timer->continue("begin pg processing") if defined($WeBWorK::timer); my $pg = WeBWorK::PG->new( - $courseEnv, + $ce, $effectiveUser, $key, $set, @@ -267,10 +342,11 @@ }, ); - $WeBWorK::timer0->continue("end pg processing") if $timer0_ON; + $WeBWorK::timer->continue("end pg processing") if defined($WeBWorK::timer); ##### fix hint/solution options ##### - $can{showHints} &&= $pg->{flags}->{hintExists}; + $can{showHints} &&= $pg->{flags}->{hintExists} + &&= $pg->{flags}->{showHintLimit}<=$pg->{state}->{num_of_incorrect_ans}; $can{showSolutions} &&= $pg->{flags}->{solutionExists}; ##### store fields ##### @@ -279,33 +355,40 @@ $self->{must} = \%must; $self->{can} = \%can; $self->{will} = \%will; - $self->{pg} = $pg; } -#sub if_warnings($$) { -# my ($self, $arg) = @_; -# return 0 unless $self->{isOpen}; -# return $self->{pg}->{warnings} ne ""; -#} - sub if_errors($$) { my ($self, $arg) = @_; - return 0 unless $self->{isOpen}; - return $self->{pg}->{flags}->{error_flag}; + + if ($self->{isOpen}) { + return $self->{pg}->{flags}->{error_flag} ? $arg : !$arg; + } else { + return !$arg; + } } sub head { - my $self = shift; + my ($self) = @_; + return "" unless $self->{isOpen}; return $self->{pg}->{head_text} if $self->{pg}->{head_text}; } sub options { - my $self = shift; + my ($self) = @_; + + return "" if $self->{invalidProblem}; + my $sourceFilePathfield = ''; + if($self->r->param("sourceFilePath")) { + $sourceFilePathfield = CGI::hidden(-name => "sourceFilePath", + -value => $self->r->param("sourceFilePath")); + } + return join("", CGI::start_form("POST", $self->{r}->uri), $self->hidden_authen_fields, + $sourceFilePathfield, CGI::hr(), CGI::start_div({class=>"viewOptions"}), $self->viewOptions(), @@ -314,100 +397,119 @@ ); } -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 = shift; - my $setName = $self->{set}->set_id; - my $problemNumber = $self->{problem}->problem_id; - - my $ce = $self->{ce}; - my $db = $self->{db}; - my $root = $ce->{webworkURLs}->{root}; - my $courseName = $ce->{courseName}; - print CGI::strong("Problems"), CGI::br(); - - 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."/?" - . $self->url_authen_args . "&displayMode=" . $self->{displayMode}}, - "Problem ".$problem), CGI::br(); + my ($self) = @_; + my $r = $self->r; + my $db = $r->db; + my $urlpath = $r->urlpath; + + # can't show sibling problems if the set is invalid + return "" if $self->{invalidSet}; + + 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, params=>{displayMode => $self->{displayMode}})}, "Problem $problemID")); } - + + print CGI::end_ul(); + print CGI::end_li(); + print CGI::end_ul(); + return ""; } sub nav { - $WeBWorK::timer0->continue("begin nav subroutine") if $timer0_ON; - my $self = shift; - my $args = $_[-1]; - my $setName = $self->{set}->set_id; - my $problemNumber = $self->{problem}->problem_id; - - my $ce = $self->{ce}; - my $db = $self->{db}; - my $root = $ce->{webworkURLs}->{root}; - my $courseName = $ce->{courseName}; + 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 if !($self->{invalidSet}); + my $problemID = $self->{problem}->problem_id if !($self->{invalidProblem}); + my $eUserID = $r->param("effectiveUser"); - my $wwdb = $self->{wwdb}; - my $effectiveUser = $self->{r}->param("effectiveUser"); - my $tail = "&displayMode=".$self->{displayMode}; + my ($prevID, $nextID); + + if (!$self->{invalidProblem}) { + 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 = ("Problem List" , "$root/$courseName/$setName", "navProbList"); + my @links; - my @problemIDs = $db->listUserProblems($effectiveUser, $setName); - my ($prevID, $nextID); - foreach my $id (@problemIDs) { - $prevID = $id if $id < $problemNumber - and (not defined $prevID or $id > $prevID); - $nextID = $id if $id > $problemNumber - and (not defined $nextID or $id < $nextID); - } - unshift @links, "Previous Problem" , ($prevID - ? "$root/$courseName/$setName/".$prevID - : "") , "navPrev"; - push @links, "Next Problem" , ($nextID - ? "$root/$courseName/$setName/".$nextID - : "") , "navNext"; - - my $result = $self->navMacro($args, $tail, @links); - $WeBWorK::timer0->continue("end nav subroutine") if $timer0_ON; - return $result; + 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 = shift; - my $setName = $self->{set}->set_id; - my $problemNumber = $self->{problem}->problem_id; + my ($self) = @_; + + # using the url arguments won't break if the set/problem are invalid + my $setID = $self->r->urlpath->arg("setID"); + my $problemID = $self->r->urlpath->arg("problemID"); - return "$setName : Problem $problemNumber"; + return "$setID : $problemID"; } sub body { my $self = shift; - - return CGI::p(CGI::font({-color=>"red"}, "This problem is not available because the problem set that contains it is not yet open.")) - unless $self->{isOpen}; - + my $r = $self->r; + my $ce = $r->ce; + my $db = $r->db; + my $authz = $r->authz; + my $urlpath = $r->urlpath; + my $user = $r->param('user'); + + if ($self->{invalidSet}) { + return CGI::div({class=>"ResultsWithError"}, + CGI::p("The selected problem set (" . $urlpath->arg("setID") . ") is not a valid set for " . $r->param("effectiveUser") . ".")); + } + + if ($self->{invalidProblem}) { + return CGI::div({class=>"ResultsWithError"}, + CGI::p("The selected problem (" . $urlpath->arg("problemID") . ") is not a valid problem for set " . $self->{set}->set_id . ".")); + } + + 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 $r = $self->{r}; - my $db = $self->{db}; my $set = $self->{set}; my $problem = $self->{problem}; my $editMode = $self->{editMode}; @@ -421,32 +523,49 @@ my %will = %{ $self->{will} }; my $pg = $self->{pg}; + my $courseName = $urlpath->arg("courseID"); + + my $editorLink = ""; + # if we are here without a real problem set, carry that through + my $forced_field = []; + $forced_field = ['sourceFilePath' => $r->param("sourceFilePath")] if + ($set->set_id eq 'Undefined_Set'); + if ($authz->hasPermissions($user, "modify_problem_sets")) { + my $editorPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::PGProblemEditor", + courseID => $courseName, setID => $set->set_id, problemID => $problem->problem_id); + my $editorURL = $self->systemLink($editorPage, params=>$forced_field); + $editorLink = CGI::a({href=>$editorURL}, "Edit this problem"); + } + ##### translation errors? ##### if ($pg->{flags}->{error_flag}) { - return $self->errorOutput($pg->{errors}, $pg->{body_text}); + print $self->errorOutput($pg->{errors}, $pg->{body_text}); + print $editorLink; + return ""; } ##### answer processing ##### - $WeBWorK::timer0->continue("begin answer processing") if $timer0_ON; + $WeBWorK::timer->continue("begin answer processing") if defined($WeBWorK::timer); # if answers were submitted: my $scoreRecordedMessage; + my $pureProblem; 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); + $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{$_} = $answerHash{$_}->{original_student_ans} + $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{$_} = $r->param($_) foreach (@extra_answer_names); + $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); @@ -503,13 +622,18 @@ # logging student answers my $answer_log = $self->{ce}->{courseFiles}->{logs}->{'answer_log'}; - if ( defined($answer_log )) { + if ( defined($answer_log ) and defined($pureProblem)) { 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. + # 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, @@ -524,25 +648,25 @@ } } - $WeBWorK::timer0->continue("end answer processing") if $timer0_ON; + $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 ($authz->hasPermissions($user, "modify_problem_sets") and defined $editMode) { if ($editMode eq "temporaryFile") { print CGI::p(CGI::i("Editing temporary file: ", $problem->source_file)); } elsif ($editMode eq "savedFile") { - print CGI::p(CGI::i("Problem saved to: ", $problem->source_file)); + # taken care of in the initialization phase } } - + # 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?? + # do I need to check $will{showCorrectAnswers} to make preflight work?? if (($pg->{flags}->{showPartialCorrectAnswers}>= 0 and $submitAnswers) ) { # print this if user submitted answers OR requested correct answers @@ -551,7 +675,7 @@ $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 CGI::div({class=>'ResultsWithError'},"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 @@ -559,7 +683,7 @@ # 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); + print CGI::div({class=>'ResultsWithError'},"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) @@ -569,7 +693,7 @@ print CGI::end_div(); print CGI::start_div({class=>"problem"}); - + # main form print CGI::startform("POST", $r->uri), @@ -585,11 +709,11 @@ ) ." " : "" ), ($can{showHints} - ? CGI::checkbox( + ? '
'. CGI::checkbox( -name => "showHints", -checked => $will{showHints}, -label => "Show Hints", - ) . " " + ) . "
" : " " ), ($can{showSolutions} ? CGI::checkbox( @@ -610,7 +734,7 @@ : ""), ); print CGI::end_div(); - + print CGI::start_div({class=>"scoreSummary"}); # score summary @@ -632,59 +756,74 @@ if (time < $set->open_date or time > $set->due_date) { $setClosed = 1; $setClosedMessage = "This problem set is closed."; - if ($permissionLevel > 0) { + if ($authz->hasPermissions($user, "view_answers")) { $setClosedMessage .= " However, since you are a privileged user, additional attempts will be recorded."; } else { $setClosedMessage .= " Additional attempts will not be recorded."; } } + + my $notCountedMessage = ($problem->value) ? "" : "(This problem will not count towards your grade.)"; 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() + ? "Your recorded score is $lastScore. $notCountedMessage" . CGI::br() : "", $setClosed ? $setClosedMessage : "You have $attemptsLeft $attemptsLeftNoun remaining." ); print CGI::end_div(); # save state for viewOptions - print CGI::hidden( - -name => "showOldAnswers", - -value => $will{showOldAnswers} - ), - - CGI::hidden( - -name => "displayMode", - -value => $self->{displayMode} - ); - + print CGI::hidden( + -name => "showOldAnswers", + -value => $will{showOldAnswers} + ), + + CGI::hidden( + -name => "displayMode", + -value => $self->{displayMode} + ); + print( CGI::hidden( + -name => 'editMode', + -value => $self->{editMode}, + ) + ) if defined($self->{editMode}) and $self->{editMode} eq 'temporaryFile'; + print( CGI::hidden( + -name => 'sourceFilePath', + -value => $self->{problem}->{source_file} + )) if defined($self->{problem}->{source_file}); + + print( CGI::hidden( + -name => 'problemSeed', + -value => $r->param("problemSeed") + )) if defined($r->param("problemSeed")); + # end of main form print CGI::endform(); - # stuff we need below (pull these out at the beginning?) - my $ce = $self->{ce}; - my $root = $ce->{webworkURLs}->{root}; - my $courseName = $ce->{courseName}; - print CGI::start_div({class=>"problemFooter"}); - # 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 = "$webworkURL/$courseName/instructor/show_answers/"; - + ## 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 = "$webworkURL/$courseName/instructor/show_answers/"; + + my $pastAnswersPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::ShowAnswers", + courseID => $courseName); + my $showPastAnswersURL = $self->systemLink($pastAnswersPage, authen => 0); # no authen info for form action + # print answer inspection button - if ($self->{permissionLevel} > 0) { + if ($authz->hasPermissions($user, "view_answers")) { print "\n", 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 => 'problemNumber', -value=>$problem->problem_id), "\n", - CGI::hidden(-name => 'setName', -value=>$problem->set_id), "\n", + CGI::hidden(-name => 'courseID', -value=>$courseName), "\n", + CGI::hidden(-name => 'problemID', -value=>$problem->problem_id), "\n", + CGI::hidden(-name => 'setID', -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') @@ -692,12 +831,10 @@ CGI::endform(); } - #print CGI::end_div(); - # - #print CGI::start_div(); - - # arguments for feedback form - my $feedbackURL = "$root/$courseName/feedback/"; + # feedback form url + my $feedbackPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Feedback", + courseID => $courseName); + my $feedbackURL = $self->systemLink($feedbackPage, authen => 0); # no authen info for form action #print feedback form print @@ -715,21 +852,12 @@ CGI::submit(-name=>"feedbackForm", -label=>"Email instructor") ), CGI::endform(),"\n"; - + # FIXME print editor link - # print editor link if the user is an instructor AND the file is not in temporary editing mode - if ($self->{permissionLevel}>=10 and ( (not defined($self->{edit_mode})) or $self->{edit_mode} eq 'savedFile') ) { - print CGI::a({-href=>$ce->{webworkURLs}->{root}."/$courseName/instructor/pgProblemEditor/".$set->set_id. - '/'.$problem->problem_id.'?'.$self->url_authen_args},'Edit this problem'); - } + print $editorLink; #empty unless it is appropriate to have an editor link. print CGI::end_div(); - # warning output - #if ($pg->{warnings} ne "") { - # print CGI::hr(), $self->warningOutput($pg->{warnings}); - #} - # debugging stuff if (0) { print @@ -752,7 +880,7 @@ ##### output utilities ##### -sub attemptResults($$$$$$) { +sub attemptResults { my $self = shift; my $pg = shift; my $showAttemptAnswers = shift; @@ -760,21 +888,29 @@ my $showAttemptResults = $showAttemptAnswers && shift; my $showSummary = shift; my $showAttemptPreview = shift || 0; - my $ce = $self->{ce}; + + my $ce = $self->r->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 $basename = "equation-" . $self->{set}->psvn. "." . $self->{problem}->problem_id . "-preview"; + + # to make grabbing these options easier, we'll pull them out now... + my %imagesModeOptions = %{$ce->{pg}->{displayModeOptions}->{images}}; + my $imgGen = WeBWorK::PG::ImageGenerator->new( - tempDir => $ce->{webworkDirs}->{tmp}, - latex => $ce->{externalPrograms}->{latex}, - dvipng => $ce->{externalPrograms}->{dvipng}, - useCache => 1, - cacheDir => $ce->{webworkDirs}->{equationCache}, - cacheURL => $ce->{webworkURLs}->{equationCache}, - cacheDB => $ce->{webworkFiles}->{equationCacheDB}, + tempDir => $ce->{webworkDirs}->{tmp}, + latex => $ce->{externalPrograms}->{latex}, + dvipng => $ce->{externalPrograms}->{dvipng}, + useCache => 1, + cacheDir => $ce->{webworkDirs}->{equationCache}, + cacheURL => $ce->{webworkURLs}->{equationCache}, + cacheDB => $ce->{webworkFiles}->{equationCacheDB}, + dvipng_align => $imagesModeOptions{dvipng_align}, + dvipng_depth_db => $imagesModeOptions{dvipng_depth_db}, ); my $header; @@ -783,9 +919,9 @@ $header .= $showAttemptPreview ? CGI::th("Answer Preview") : ""; $header .= $showCorrectAnswers ? CGI::th("Correct") : ""; $header .= $showAttemptResults ? CGI::th("Result") : ""; - $header .= $showMessages ? CGI::th("messages") : ""; + $header .= $showMessages ? CGI::th("Messages") : ""; my @tableRows = ( $header ); - my $numCorrect; + my $numCorrect = 0; foreach my $name (@answerNames) { my $answerResult = $pg->{answers}->{$name}; my $studentAnswer = $answerResult->{student_ans}; # original_student_ans @@ -797,7 +933,7 @@ 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"; + my $resultString = $answerScore == 1 ? "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" @@ -805,11 +941,11 @@ my $row; #$row .= CGI::td($name); - $row .= $showAttemptAnswers ? CGI::td(nbsp($studentAnswer)) : ""; - $row .= $showAttemptPreview ? CGI::td(nbsp($preview)) : ""; - $row .= $showCorrectAnswers ? CGI::td(nbsp($correctAnswer)) : ""; - $row .= $showAttemptResults ? CGI::td(nbsp($resultString)) : ""; - $row .= $answerMessage ? CGI::td(nbsp($answerMessage)) : ""; + $row .= $showAttemptAnswers ? CGI::td($self->nbsp($studentAnswer)) : ""; + $row .= $showAttemptPreview ? CGI::td($self->nbsp($preview)) : ""; + $row .= $showCorrectAnswers ? CGI::td($self->nbsp($correctAnswer)) : ""; + $row .= $showAttemptResults ? CGI::td($self->nbsp($resultString)) : ""; + $row .= $showMessages ? CGI::td($self->nbsp($answerMessage)) : ""; push @tableRows, $row; } @@ -824,31 +960,38 @@ my $summary = ""; if (scalar @answerNames == 1) { if ($numCorrect == scalar @answerNames) { - $summary .= "The above answer is correct."; + $summary .= CGI::div({class=>"ResultsWithoutError"},"The above answer is correct."); } else { - $summary .= "The above answer is NOT correct."; + $summary .= CGI::div({class=>"ResultsWithError"},"The above answer is NOT correct."); } } else { if ($numCorrect == scalar @answerNames) { - $summary .= "All of the above answers are correct."; + $summary .= CGI::div({class=>"ResultsWithoutError"},"All of the above answers are correct."); } else { - $summary .= "At least one of the above answers is NOT correct."; + $summary .= CGI::div({class=>"ResultsWithError"},"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 =~/\S/) ? $str : ' ' ; # returns non-breaking space for empty strings - # tricky cases: $str =0; - # $str is a complex number + + return + CGI::table({-class=>"attemptResults"}, CGI::Tr(\@tableRows)) + . ($showSummary ? CGI::p({class=>'emphasis'},$summary) : ""); } -sub viewOptions($) { - my $self = shift; + +#sub nbsp { +# my $str = shift; +# ($str =~/\S/) ? $str : ' ' ; # returns non-breaking space for empty strings +# # tricky cases: $str =0; +# # $str is a complex number +#} + +sub viewOptions { + my ($self) = @_; + my $ce = $self->r->ce; + + # don't show options if we don't have anything to show + return if $self->{invalidSet} or $self->{invalidProblem}; + return unless $self->{isOpen}; + my $displayMode = $self->{displayMode}; my %must = %{ $self->{must} }; my %can = %{ $self->{can} }; @@ -865,27 +1008,35 @@ $optionLine and $optionLine .= join "", CGI::br(); - return CGI::div({-style=>"border: thin groove; padding: 1ex; margin: 2ex align: left"}, - "View equations as:    ".CGI::br(), + my %display_modes = %{WeBWorK::PG::DISPLAY_MODES()}; + my @active_modes = grep { exists $display_modes{$_} } + @{$ce->{pg}->{displayModes}}; + my $modeLine = (scalar(@active_modes)>1) ? + "View equations as:    ".CGI::br(). CGI::radio_group( -name => "displayMode", - -values => ['plainText', 'formattedText', 'images'], + -values => \@active_modes, -default => $displayMode, -linebreak=>'true', -labels => { plainText => "plain", formattedText => "formatted", images => "images", - } - ), CGI::br(),CGI::hr(), + jsMath => "jsMath", + asciimath => "asciimath", + }, + ). CGI::br().CGI::hr() : ''; + + return CGI::div({-style=>"border: thin groove; padding: 1ex; margin: 2ex align: left"}, + $modeLine, $optionLine, CGI::submit(-name=>"redisplay", -label=>"Save Options"), ); } -sub previewAnswer($$) { +sub previewAnswer { my ($self, $answerResult, $imgGen) = @_; - my $ce = $self->{ce}; + my $ce = $self->r->ce; my $effectiveUser = $self->{effectiveUser}; my $set = $self->{set}; my $problem = $self->{problem}; @@ -915,39 +1066,17 @@ } 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]"; - #} - $imgGen->add($answerResult->{preview_latex_string}); - - } + $imgGen->add($tex); + } elsif ($displayMode eq "jsMath") { + + return '
'.$tex.'
' ; + + + + + } } -##### logging subroutine #### - - - ##### permission queries ##### # this stuff should be abstracted out into the permissions system @@ -956,7 +1085,7 @@ # also, i should fix these so that they have a consistent calling # format -- perhaps: -# canPERM($courseEnv, $user, $set, $problem, $permissionLevel) +# canPERM($ce, $user, $set, $problem, $permissionLevel) sub canShowCorrectAnswers($$) { my ($permissionLevel, $answerDate) = @_; @@ -978,9 +1107,9 @@ } sub canCheckAnswers($$) { - my ($permissionLevel, $answerDate) = @_; + my ($permissionLevel, $dueDate) = @_; my $permHigh = $permissionLevel > 0; - my $timeOK = time >= $answerDate; + my $timeOK = time >= $dueDate; my $recordAnswers = $permHigh || $timeOK; return $recordAnswers; } @@ -989,5 +1118,4 @@ my ($permissionLevel) = @_; return $permissionLevel == 0; } - 1;