[system] / branches / gage_dev / webwork2 / lib / WeBWorK / ContentGenerator / Problem.pm Repository:
ViewVC logotype

View of /branches/gage_dev/webwork2/lib/WeBWorK/ContentGenerator/Problem.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 6275 - (download) (as text) (annotate)
Tue May 25 22:04:13 2010 UTC (2 years, 11 months ago) by gage
Original Path: trunk/webwork2/lib/WeBWorK/ContentGenerator/Problem.pm
File size: 45622 byte(s)
Remove unneeded warning.

    1 ################################################################################
    2 # WeBWorK Online Homework Delivery System
    3 # Copyright © 2000-2007 The WeBWorK Project, http://openwebwork.sf.net/
    4 # $CVSHeader: webwork2/lib/WeBWorK/ContentGenerator/Problem.pm,v 1.223 2010/05/25 18:22:12 gage Exp $
    5 #
    6 # This program is free software; you can redistribute it and/or modify it under
    7 # the terms of either: (a) the GNU General Public License as published by the
    8 # Free Software Foundation; either version 2, or (at your option) any later
    9 # version, or (b) the "Artistic License" which comes with this package.
   10 #
   11 # This program is distributed in the hope that it will be useful, but WITHOUT
   12 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
   13 # FOR A PARTICULAR PURPOSE.  See either the GNU General Public License or the
   14 # Artistic License for more details.
   15 ################################################################################
   16 
   17 package WeBWorK::ContentGenerator::Problem;
   18 use base qw(WeBWorK::ContentGenerator);
   19 
   20 =head1 NAME
   21 
   22 WeBWorK::ContentGenerator::Problem - Allow a student to interact with a problem.
   23 
   24 =cut
   25 
   26 use strict;
   27 use warnings;
   28 #use CGI qw(-nosticky );
   29 use WeBWorK::CGI;
   30 use File::Path qw(rmtree);
   31 use WeBWorK::Debug;
   32 use WeBWorK::Form;
   33 use WeBWorK::PG;
   34 use WeBWorK::PG::ImageGenerator;
   35 use WeBWorK::PG::IO;
   36 use WeBWorK::Utils qw(readFile writeLog writeCourseLog encodeAnswers decodeAnswers
   37   ref2string makeTempDirectory path_is_subdir sortByName before after between);
   38 use WeBWorK::DB::Utils qw(global2user user2global);
   39 use URI::Escape;
   40 
   41 use WeBWorK::Utils::Tasks qw(fake_set fake_problem);
   42 
   43 ################################################################################
   44 # CGI param interface to this module (up-to-date as of v1.153)
   45 ################################################################################
   46 
   47 # Standard params:
   48 #
   49 #     user - user ID of real user
   50 #     key - session key
   51 #     effectiveUser - user ID of effective user
   52 #
   53 # Integration with PGProblemEditor:
   54 #
   55 #     editMode - if set, indicates alternate problem source location.
   56 #                can be "temporaryFile" or "savedFile".
   57 #
   58 #     sourceFilePath - path to file to be edited
   59 #     problemSeed - force problem seed to value
   60 #     success - success message to display
   61 #     failure - failure message to display
   62 #
   63 # Rendering options:
   64 #
   65 #     displayMode - name of display mode to use
   66 #
   67 #     showOldAnswers - request that last entered answer be shown (if allowed)
   68 #     showCorrectAnswers - request that correct answers be shown (if allowed)
   69 #     showHints - request that hints be shown (if allowed)
   70 #     showSolutions - request that solutions be shown (if allowed)
   71 #
   72 # Problem interaction:
   73 #
   74 #     AnSwEr# - answer blanks in problem
   75 #
   76 #     redisplay - name of the "Redisplay Problem" button
   77 #     submitAnswers - name of "Submit Answers" button
   78 #     checkAnswers - name of the "Check Answers" button
   79 #     previewAnswers - name of the "Preview Answers" button
   80 
   81 ################################################################################
   82 # "can" methods
   83 ################################################################################
   84 
   85 # Subroutines to determine if a user "can" perform an action. Each subroutine is
   86 # called with the following arguments:
   87 #
   88 #     ($self, $User, $EffectiveUser, $Set, $Problem)
   89 
   90 # Note that significant parts of the "can" methods are lifted into the
   91 # GatewayQuiz module.  It isn't direct, however, because of the necessity
   92 # of dealing with versioning there.
   93 
   94 sub can_showOldAnswers {
   95   #my ($self, $User, $EffectiveUser, $Set, $Problem) = @_;
   96 
   97   return 1;
   98 }
   99 
  100 sub can_showCorrectAnswers {
  101   my ($self, $User, $EffectiveUser, $Set, $Problem) = @_;
  102   my $authz = $self->r->authz;
  103 
  104   return
  105     after($Set->answer_date)
  106       ||
  107     $authz->hasPermissions($User->user_id, "show_correct_answers_before_answer_date")
  108     ;
  109 }
  110 
  111 sub can_showHints {
  112   #my ($self, $User, $EffectiveUser, $Set, $Problem) = @_;
  113 
  114   return 1;
  115 }
  116 
  117 sub can_showSolutions {
  118   my ($self, $User, $EffectiveUser, $Set, $Problem) = @_;
  119   my $authz = $self->r->authz;
  120 
  121   return
  122     after($Set->answer_date)
  123       ||
  124     $authz->hasPermissions($User->user_id, "show_solutions_before_answer_date")
  125     ;
  126 }
  127 
  128 sub can_recordAnswers {
  129   my ($self, $User, $EffectiveUser, $Set, $Problem, $submitAnswers) = @_;
  130   my $authz = $self->r->authz;
  131   my $thisAttempt = $submitAnswers ? 1 : 0;
  132   if ($User->user_id ne $EffectiveUser->user_id) {
  133     return $authz->hasPermissions($User->user_id, "record_answers_when_acting_as_student");
  134   }
  135   if (before($Set->open_date)) {
  136     return $authz->hasPermissions($User->user_id, "record_answers_before_open_date");
  137   } elsif (between($Set->open_date, $Set->due_date)) {
  138     my $max_attempts = $Problem->max_attempts;
  139     my $attempts_used = $Problem->num_correct + $Problem->num_incorrect + $thisAttempt;
  140     if ($max_attempts == -1 or $attempts_used < $max_attempts) {
  141       return $authz->hasPermissions($User->user_id, "record_answers_after_open_date_with_attempts");
  142     } else {
  143       return $authz->hasPermissions($User->user_id, "record_answers_after_open_date_without_attempts");
  144     }
  145   } elsif (between($Set->due_date, $Set->answer_date)) {
  146     return $authz->hasPermissions($User->user_id, "record_answers_after_due_date");
  147   } elsif (after($Set->answer_date)) {
  148     return $authz->hasPermissions($User->user_id, "record_answers_after_answer_date");
  149   }
  150 }
  151 
  152 sub can_checkAnswers {
  153   my ($self, $User, $EffectiveUser, $Set, $Problem, $submitAnswers) = @_;
  154   my $authz = $self->r->authz;
  155   my $thisAttempt = $submitAnswers ? 1 : 0;
  156 
  157   if (before($Set->open_date)) {
  158     return $authz->hasPermissions($User->user_id, "check_answers_before_open_date");
  159   } elsif (between($Set->open_date, $Set->due_date)) {
  160     my $max_attempts = $Problem->max_attempts;
  161     my $attempts_used = $Problem->num_correct + $Problem->num_incorrect + $thisAttempt;
  162     if ($max_attempts == -1 or $attempts_used < $max_attempts) {
  163       return $authz->hasPermissions($User->user_id, "check_answers_after_open_date_with_attempts");
  164     } else {
  165       return $authz->hasPermissions($User->user_id, "check_answers_after_open_date_without_attempts");
  166     }
  167   } elsif (between($Set->due_date, $Set->answer_date)) {
  168     return $authz->hasPermissions($User->user_id, "check_answers_after_due_date");
  169   } elsif (after($Set->answer_date)) {
  170     return $authz->hasPermissions($User->user_id, "check_answers_after_answer_date");
  171   }
  172 }
  173 
  174 # Reset the default in some cases
  175 sub set_showOldAnswers_default {
  176   my ($self, $ce, $userName, $authz, $set) = @_;
  177   # these people always use the system/course default, so don't
  178   # override the value of ...->{showOldAnswers}
  179   return if $authz->hasPermissions($userName, "can_always_use_show_old_answers_default");
  180   # this person should always default to 0
  181   $ce->{pg}->{options}->{showOldAnswers} = 0
  182     unless ($authz->hasPermissions($userName, "can_show_old_answers_by_default"));
  183   # we are after the due date, so default to not showing it
  184   $ce->{pg}->{options}->{showOldAnswers} = 0 if $set->{due_date} && after($set->{due_date});
  185 }
  186 
  187 ################################################################################
  188 # output utilities
  189 ################################################################################
  190 
  191 # Note: the substance of attemptResults is lifted into GatewayQuiz.pm,
  192 # with some changes to the output format
  193 
  194 sub attemptResults {
  195   my $self = shift;
  196   my $pg = shift;
  197   my $showAttemptAnswers = shift;
  198   my $showCorrectAnswers = shift;
  199   my $showAttemptResults = $showAttemptAnswers && shift;
  200   my $showSummary = shift;
  201   my $showAttemptPreview = shift || 0;
  202 
  203   my $ce = $self->r->ce;
  204 
  205   my $problemResult = $pg->{result}; # the overall result of the problem
  206   my @answerNames = @{ $pg->{flags}->{ANSWER_ENTRY_ORDER} };
  207 
  208   my $showMessages = $showAttemptAnswers && grep { $pg->{answers}->{$_}->{ans_message} } @answerNames;
  209 
  210   my $basename = "equation-" . $self->{set}->psvn. "." . $self->{problem}->problem_id . "-preview";
  211 
  212   # to make grabbing these options easier, we'll pull them out now...
  213   my %imagesModeOptions = %{$ce->{pg}->{displayModeOptions}->{images}};
  214 
  215   my $imgGen = WeBWorK::PG::ImageGenerator->new(
  216     tempDir         => $ce->{webworkDirs}->{tmp},
  217     latex         => $ce->{externalPrograms}->{latex},
  218     dvipng          => $ce->{externalPrograms}->{dvipng},
  219     useCache        => 1,
  220     cacheDir        => $ce->{webworkDirs}->{equationCache},
  221     cacheURL        => $ce->{webworkURLs}->{equationCache},
  222     cacheDB         => $ce->{webworkFiles}->{equationCacheDB},
  223     dvipng_align    => $imagesModeOptions{dvipng_align},
  224     dvipng_depth_db => $imagesModeOptions{dvipng_depth_db},
  225   );
  226 
  227   my $header;
  228   #$header .= CGI::th("Part");
  229   $header .= $showAttemptAnswers ? CGI::th("Entered")  : "";
  230   $header .= $showAttemptPreview ? CGI::th("Answer Preview")  : "";
  231   $header .= $showCorrectAnswers ? CGI::th("Correct")  : "";
  232   $header .= $showAttemptResults ? CGI::th("Result")   : "";
  233   $header .= $showMessages       ? CGI::th("Messages") : "";
  234   my $fully = '';
  235   my @tableRows = ( $header );
  236   my $numCorrect = 0;
  237   my $numBlanks  =0;
  238   my $tthPreambleCache;
  239   foreach my $name (@answerNames) {
  240     my $answerResult  = $pg->{answers}->{$name};
  241     my $studentAnswer = $answerResult->{student_ans}; # original_student_ans
  242     my $preview       = ($showAttemptPreview
  243                           ? $self->previewAnswer($answerResult, $imgGen, \$tthPreambleCache)
  244                           : "");
  245     my $correctAnswer = $answerResult->{correct_ans};
  246     my $answerScore   = $answerResult->{score};
  247     my $answerMessage = $showMessages ? $answerResult->{ans_message} : "";
  248     $answerMessage =~ s/\n/<BR>/g;
  249     $numCorrect += $answerScore >= 1;
  250     $numBlanks++ unless $studentAnswer =~/\S/ || $answerScore >= 1;   # unless student answer contains entry
  251     my $resultString = $answerScore >= 1 ? "correct" :
  252                        $answerScore > 0  ? int($answerScore*100)."% correct" :
  253                                                        "incorrect";
  254     $fully = 'completely ' if $answerScore >0 and $answerScore < 1;
  255 
  256     # get rid of the goofy prefix on the answer names (supposedly, the format
  257     # of the answer names is changeable. this only fixes it for "AnSwEr"
  258     #$name =~ s/^AnSwEr//;
  259 
  260     my $row;
  261     #$row .= CGI::td($name);
  262     $row .= $showAttemptAnswers ? CGI::td($self->nbsp($studentAnswer)) : "";
  263     $row .= $showAttemptPreview ? CGI::td($self->nbsp($preview))       : "";
  264     $row .= $showCorrectAnswers ? CGI::td($self->nbsp($correctAnswer)) : "";
  265     $row .= $showAttemptResults ? CGI::td($self->nbsp($resultString))  : "";
  266     $row .= $showMessages       ? CGI::td({-class=>"Message"},$self->nbsp($answerMessage)) : "";
  267     push @tableRows, $row;
  268   }
  269 
  270   # render equation images
  271   $imgGen->render(refresh => 1);
  272 
  273 # my $numIncorrectNoun = scalar @answerNames == 1 ? "question" : "questions";
  274   my $scorePercent = sprintf("%.0f%%", $problemResult->{score} * 100);
  275 #   FIXME  -- I left the old code in in case we have to back out.
  276 # my $summary = "On this attempt, you answered $numCorrect out of "
  277 #   . scalar @answerNames . " $numIncorrectNoun correct, for a score of $scorePercent.";
  278   my $summary = "";
  279   unless (defined($problemResult->{summary}) and $problemResult->{summary} =~ /\S/) {
  280     if (scalar @answerNames == 1) {  #default messages
  281         if ($numCorrect == scalar @answerNames) {
  282           $summary .= CGI::div({class=>"ResultsWithoutError"},"The answer above is correct.");
  283          } else {
  284            $summary .= CGI::div({class=>"ResultsWithError"},"The answer above is NOT ${fully}correct.");
  285          }
  286     } else {
  287         if ($numCorrect == scalar @answerNames) {
  288           $summary .= CGI::div({class=>"ResultsWithoutError"},"All of the answers above are correct.");
  289          }
  290          unless ($numCorrect + $numBlanks == scalar( @answerNames)) {
  291           $summary .= CGI::div({class=>"ResultsWithError"},"At least one of the answers above is NOT ${fully}correct.");
  292          }
  293          if ($numBlanks) {
  294           my $s = ($numBlanks>1)?'':'s';
  295           $summary .= CGI::div({class=>"ResultsAlert"},"$numBlanks of the questions remain$s unanswered.");
  296          }
  297     }
  298   } else {
  299     $summary = $problemResult->{summary};   # summary has been defined by grader
  300   }
  301   return
  302     CGI::table({-class=>"attemptResults"}, CGI::Tr(\@tableRows))
  303     . ($showSummary ? CGI::p({class=>'attemptResultsSummary'},$summary) : "");
  304 }
  305 
  306 
  307 # Note: previewAnswer is lifted into GatewayQuiz.pm
  308 
  309 sub previewAnswer {
  310   my ($self, $answerResult, $imgGen, $tthPreambleCache) = @_;
  311   my $ce            = $self->r->ce;
  312   my $effectiveUser = $self->{effectiveUser};
  313   my $set           = $self->{set};
  314   my $problem       = $self->{problem};
  315   my $displayMode   = $self->{displayMode};
  316 
  317   # note: right now, we have to do things completely differently when we are
  318   # rendering math from INSIDE the translator and from OUTSIDE the translator.
  319   # so we'll just deal with each case explicitly here. there's some code
  320   # duplication that can be dealt with later by abstracting out tth/dvipng/etc.
  321 
  322   my $tex = $answerResult->{preview_latex_string};
  323 
  324   return "" unless defined $tex and $tex ne "";
  325 
  326   if ($displayMode eq "plainText") {
  327     return $tex;
  328   } elsif ($displayMode eq "formattedText") {
  329 
  330     # read the TTH preamble, or use the cached copy passed in from the caller
  331     my $tthPreamble='';
  332     if (defined $$tthPreambleCache) {
  333       $tthPreamble = $$tthPreambleCache;
  334     } else {
  335       my $tthPreambleFile = $ce->{courseDirs}->{templates} . "/tthPreamble.tex";
  336       if (-r $tthPreambleFile) {
  337         $tthPreamble = readFile($tthPreambleFile);
  338         # thanks to Jim Martino. each line in the definition file should end with
  339         #a % to prevent adding supurious paragraphs to output:
  340         $tthPreamble =~ s/(.)\n/$1%\n/g;
  341         # solves the problem if the file doesn't end with a return:
  342         $tthPreamble .="%\n";
  343         # store preamble in cache:
  344         $$tthPreambleCache = $tthPreamble;
  345       } else {
  346       }
  347     }
  348 
  349     # construct TTH command line
  350     my $tthCommand = $ce->{externalPrograms}->{tth}
  351       . " -L -f5 -u -r  2> /dev/null <<END_OF_INPUT; echo > /dev/null\n"
  352       . $tthPreamble . "\\[" . $tex . "\\]\n"
  353       . "END_OF_INPUT\n";
  354 
  355     # call tth
  356     my $result = `$tthCommand`;
  357     if ($?) {
  358       return "<b>[tth failed: $? $@]</b>";
  359     } else {
  360       #  avoid border problems in tables and remove unneeded initial <br>
  361       $result =~ s/(<table [^>]*)>/$1 CLASS="ArrayLayout">/gi;
  362       $result =~ s!\s*<br clear="all" />!!;
  363       return $result;
  364     }
  365 
  366   } elsif ($displayMode eq "images") {
  367     $imgGen->add($tex);
  368   } elsif ($displayMode eq "jsMath") {
  369     $tex =~ s/</&lt;/g; $tex =~ s/>/&gt;/g;
  370     return '<SPAN CLASS="math">\\displaystyle{'.$tex.'}</SPAN>';
  371   }
  372 }
  373 
  374 ################################################################################
  375 # Template escape implementations
  376 ################################################################################
  377 
  378 sub pre_header_initialize {
  379   my ($self) = @_;
  380   my $r = $self->r;
  381   my $ce = $r->ce;
  382   my $db = $r->db;
  383   my $authz = $r->authz;
  384   my $urlpath = $r->urlpath;
  385 
  386   my $setName = $urlpath->arg("setID");
  387   my $problemNumber = $r->urlpath->arg("problemID");
  388   my $userName = $r->param('user');
  389   my $effectiveUserName = $r->param('effectiveUser');
  390   my $key = $r->param('key');
  391   my $editMode = $r->param("editMode");
  392 
  393   my $user = $db->getUser($userName); # checked
  394   die "record for user $userName (real user) does not exist."
  395     unless defined $user;
  396 
  397   my $effectiveUser = $db->getUser($effectiveUserName); # checked
  398   die "record for user $effectiveUserName (effective user) does not exist."
  399     unless defined $effectiveUser;
  400 
  401   # obtain the merged set for $effectiveUser
  402   my $set = $db->getMergedSet($effectiveUserName, $setName); # checked
  403 
  404   $self->set_showOldAnswers_default($ce, $userName, $authz, $set);
  405 
  406   # Database fix (in case of undefined published values)
  407   # this is only necessary because some people keep holding to ww1.9 which did not have a published field
  408   # make sure published is set to 0 or 1
  409   if ( $set and $set->published ne "0" and $set->published ne "1") {
  410     my $globalSet = $db->getGlobalSet($set->set_id);
  411     $globalSet->published("1"); # defaults to published
  412     $db->putGlobalSet($globalSet);
  413     $set = $db->getMergedSet($effectiveUserName, $setName);
  414   } else {
  415     # don't do anything just yet, maybe we're a professor and we're
  416     # fabricating a set or haven't assigned it to ourselves just yet
  417   }
  418     # When a set is created enable_reduced_scoring is null, so we have to set it
  419   if ( $set and $set->enable_reduced_scoring ne "0" and $set->enable_reduced_scoring ne "1") {
  420     my $globalSet = $db->getGlobalSet($set->set_id);
  421     $globalSet->enable_reduced_scoring("0");  # defaults to disabled
  422     $db->putGlobalSet($globalSet);
  423     $set = $db->getMergedSet($effectiveUserName, $setName);
  424   }
  425 
  426 
  427   # obtain the merged problem for $effectiveUser
  428   my $problem = $db->getMergedProblem($effectiveUserName, $setName, $problemNumber); # checked
  429 
  430   if ($authz->hasPermissions($userName, "modify_problem_sets")) {
  431     # professors are allowed to fabricate sets and problems not
  432     # assigned to them (or anyone). this allows them to use the
  433     # editor to
  434 
  435     # if a User Set does not exist for this user and this set
  436     # then we check the Global Set
  437     # if that does not exist we create a fake set
  438     # if it does, we add fake user data
  439     unless (defined $set) {
  440       my $userSetClass = $db->{set_user}->{record};
  441       my $globalSet = $db->getGlobalSet($setName); # checked
  442 
  443       if (not defined $globalSet) {
  444         $set = fake_set($db);
  445       } else {
  446         $set = global2user($userSetClass, $globalSet);
  447         $set->psvn(0);
  448       }
  449     }
  450 
  451     # if that is not yet defined obtain the global problem,
  452     # convert it to a user problem, and add fake user data
  453     unless (defined $problem) {
  454       my $userProblemClass = $db->{problem_user}->{record};
  455       my $globalProblem = $db->getGlobalProblem($setName, $problemNumber); # checked
  456       # if the global problem doesn't exist either, bail!
  457       if(not defined $globalProblem) {
  458         my $sourceFilePath = $r->param("sourceFilePath");
  459         die "sourceFilePath is unsafe!" unless path_is_subdir($sourceFilePath, $ce->{courseDirs}->{templates}, 1); # 1==path can be relative to dir
  460         # These are problems from setmaker.  If declared invalid, they won't come up
  461         $self->{invalidProblem} = $self->{invalidSet} = 1 unless defined $sourceFilePath;
  462 #       die "Problem $problemNumber in set $setName does not exist" unless defined $sourceFilePath;
  463         $problem = fake_problem($db);
  464         $problem->problem_id(1);
  465         $problem->source_file($sourceFilePath);
  466         $problem->user_id($effectiveUserName);
  467       } else {
  468         $problem = global2user($userProblemClass, $globalProblem);
  469         $problem->user_id($effectiveUserName);
  470         $problem->problem_seed(0);
  471         $problem->status(0);
  472         $problem->attempted(0);
  473         $problem->last_answer("");
  474         $problem->num_correct(0);
  475         $problem->num_incorrect(0);
  476       }
  477     }
  478 
  479     # now we're sure we have valid UserSet and UserProblem objects
  480     # yay!
  481 
  482     # now deal with possible editor overrides:
  483 
  484     # if the caller is asking to override the source file, and
  485     # editMode calls for a temporary file, do so
  486     my $sourceFilePath = $r->param("sourceFilePath");
  487     if (defined $editMode and $editMode eq "temporaryFile" and defined $sourceFilePath) {
  488       die "sourceFilePath is unsafe!" unless path_is_subdir($sourceFilePath, $ce->{courseDirs}->{templates}, 1); # 1==path can be relative to dir
  489       $problem->source_file($sourceFilePath);
  490     }
  491 
  492     # if the problem does not have a source file or no source file has been passed in
  493     # then this is really an invalid problem (probably from a bad URL)
  494     $self->{invalidProblem} = not (defined $sourceFilePath or $problem->source_file);
  495 
  496     # if the caller is asking to override the problem seed, do so
  497     my $problemSeed = $r->param("problemSeed");
  498     if (defined $problemSeed) {
  499       $problem->problem_seed($problemSeed);
  500     }
  501 
  502     my $publishedClass = ($set->published) ? "Published" : "Unpublished";
  503     my $publishedText = ($set->published) ? "visible to students." : "hidden from students.";
  504     $self->addmessage(CGI::span("This set is " . CGI::font({class=>$publishedClass}, $publishedText)));
  505 
  506   # test for additional problem validity if it's not already invalid
  507         } else {
  508     $self->{invalidProblem} = !(defined $problem and ($set->published || $authz->hasPermissions($userName, "view_unpublished_sets")));
  509 
  510     $self->addbadmessage(CGI::p("This problem will not count towards your grade.")) if $problem and not $problem->value and not $self->{invalidProblem};
  511   }
  512 
  513   $self->{userName}          = $userName;
  514   $self->{effectiveUserName} = $effectiveUserName;
  515   $self->{user}              = $user;
  516   $self->{effectiveUser}     = $effectiveUser;
  517   $self->{set}               = $set;
  518   $self->{problem}           = $problem;
  519   $self->{editMode}          = $editMode;
  520 
  521   ##### form processing #####
  522 
  523   # set options from form fields (see comment at top of file for names)
  524   my $displayMode        = $r->param("displayMode") || $ce->{pg}->{options}->{displayMode};
  525   my $redisplay          = $r->param("redisplay");
  526   my $submitAnswers      = $r->param("submitAnswers");
  527   my $checkAnswers       = $r->param("checkAnswers");
  528   my $previewAnswers     = $r->param("previewAnswers");
  529 
  530   my $formFields = { WeBWorK::Form->new_from_paramable($r)->Vars };
  531 
  532   $self->{displayMode}    = $displayMode;
  533   $self->{redisplay}      = $redisplay;
  534   $self->{submitAnswers}  = $submitAnswers;
  535   $self->{checkAnswers}   = $checkAnswers;
  536   $self->{previewAnswers} = $previewAnswers;
  537   $self->{formFields}     = $formFields;
  538 
  539   # get result and send to message
  540   my $status_message = $r->param("status_message");
  541   $self->addmessage(CGI::p("$status_message")) if $status_message;
  542 
  543   # now that we've set all the necessary variables quit out if the set or problem is invalid
  544   return if $self->{invalidSet} || $self->{invalidProblem};
  545 
  546   ##### permissions #####
  547 
  548   # what does the user want to do?
  549   #FIXME  There is a problem with checkboxes -- if they are not checked they are invisible.  Hence if the default mode in $ce is 1
  550   # there is no way to override this.  Probably this is ok for the last three options, but it was definitely not ok for showing
  551   # saved answers which is normally on, but you want to be able to turn it off!  This section should be moved to ContentGenerator
  552   # so that you can set these options anywhere.  We also need mechanisms for making them sticky.
  553   # Note: ProblemSet and ProblemSets might set showOldAnswers to '', which
  554   #       needs to be treated as if it is not set.
  555   my %want = (
  556     showOldAnswers     => (defined($r->param("showOldAnswers")) and $r->param("showOldAnswers") ne '') ? $r->param("showOldAnswers")  : $ce->{pg}->{options}->{showOldAnswers},
  557     showCorrectAnswers => $r->param("showCorrectAnswers") || $ce->{pg}->{options}->{showCorrectAnswers},
  558     showHints          => $r->param("showHints")          || $ce->{pg}->{options}->{showHints},
  559     showSolutions      => $r->param("showSolutions")      || $ce->{pg}->{options}->{showSolutions},
  560     recordAnswers      => $submitAnswers,
  561     checkAnswers       => $checkAnswers,
  562     getSubmitButton    => 1,
  563   );
  564 
  565   # are certain options enforced?
  566   my %must = (
  567     showOldAnswers     => 0,
  568     showCorrectAnswers => 0,
  569     showHints          => 0,
  570     showSolutions      => 0,
  571     recordAnswers      => ! $authz->hasPermissions($userName, "avoid_recording_answers"),
  572     checkAnswers       => 0,
  573     getSubmitButton    => 0,
  574   );
  575 
  576   # does the user have permission to use certain options?
  577   my @args = ($user, $effectiveUser, $set, $problem);
  578   my %can = (
  579     showOldAnswers     => $self->can_showOldAnswers(@args),
  580     showCorrectAnswers => $self->can_showCorrectAnswers(@args),
  581     showHints          => $self->can_showHints(@args),
  582     showSolutions      => $self->can_showSolutions(@args),
  583     recordAnswers      => $self->can_recordAnswers(@args, 0),
  584     checkAnswers       => $self->can_checkAnswers(@args, $submitAnswers),
  585     getSubmitButton    => $self->can_recordAnswers(@args, $submitAnswers),
  586   );
  587 
  588   # final values for options
  589   my %will;
  590   foreach (keys %must) {
  591     $will{$_} = $can{$_} && ($want{$_} || $must{$_});
  592     #warn "final values for options $_ is can $can{$_}, want $want{$_}, must $must{$_}, will $will{$_}";
  593   }
  594 
  595   ##### sticky answers #####
  596 
  597   if (not ($submitAnswers or $previewAnswers or $checkAnswers) and $will{showOldAnswers}) {
  598     # do this only if new answers are NOT being submitted
  599     my %oldAnswers = decodeAnswers($problem->last_answer);
  600     $formFields->{$_} = $oldAnswers{$_} foreach keys %oldAnswers;
  601   }
  602 
  603   ##### translation #####
  604 
  605   debug("begin pg processing");
  606   my $pg = WeBWorK::PG->new(
  607     $ce,
  608     $effectiveUser,
  609     $key,
  610     $set,
  611     $problem,
  612     $set->psvn, # FIXME: this field should be removed
  613     $formFields,
  614     { # translation options
  615       displayMode     => $displayMode,
  616       showHints       => $will{showHints},
  617       showSolutions   => $will{showSolutions},
  618       refreshMath2img => $will{showHints} || $will{showSolutions},
  619       processAnswers  => 1,
  620       permissionLevel => $db->getPermissionLevel($userName)->permission,
  621       effectivePermissionLevel => $db->getPermissionLevel($effectiveUserName)->permission,
  622     },
  623   );
  624 
  625   debug("end pg processing");
  626 
  627   ##### fix hint/solution options #####
  628 
  629   $can{showHints}     &&= $pg->{flags}->{hintExists}
  630                       &&= $pg->{flags}->{showHintLimit}<=$pg->{state}->{num_of_incorrect_ans};
  631   $can{showSolutions} &&= $pg->{flags}->{solutionExists};
  632 
  633   ##### store fields #####
  634 
  635   $self->{want} = \%want;
  636   $self->{must} = \%must;
  637   $self->{can}  = \%can;
  638   $self->{will} = \%will;
  639   $self->{pg} = $pg;
  640 }
  641 
  642 sub if_errors($$) {
  643   my ($self, $arg) = @_;
  644 
  645   if ($self->{isOpen}) {
  646     return $self->{pg}->{flags}->{error_flag} ? $arg : !$arg;
  647   } else {
  648     return !$arg;
  649   }
  650 }
  651 
  652 sub head {
  653   my ($self) = @_;
  654 
  655   return "" if ( $self->{invalidSet} );
  656   return $self->{pg}->{head_text} if $self->{pg}->{head_text};
  657 }
  658 
  659 sub options {
  660   my ($self) = @_;
  661   #warn "doing options in Problem";
  662 
  663   # don't show options if we don't have anything to show
  664   return "" if $self->{invalidSet} or $self->{invalidProblem};
  665 
  666   my $displayMode = $self->{displayMode};
  667   my %can = %{ $self->{can} };
  668 
  669   my @options_to_show = "displayMode";
  670   push @options_to_show, "showOldAnswers" if $can{showOldAnswers};
  671   push @options_to_show, "showHints" if $can{showHints};
  672   push @options_to_show, "showSolutions" if $can{showSolutions};
  673 
  674   return $self->optionsMacro(
  675     options_to_show => \@options_to_show,
  676     extra_params => ["editMode", "sourceFilePath"],
  677   );
  678 }
  679 
  680 sub siblings {
  681   my ($self) = @_;
  682   my $r = $self->r;
  683   my $db = $r->db;
  684   my $urlpath = $r->urlpath;
  685 
  686   # can't show sibling problems if the set is invalid
  687   return "" if $self->{invalidSet};
  688 
  689   my $courseID = $urlpath->arg("courseID");
  690   my $setID = $self->{set}->set_id;
  691   my $eUserID = $r->param("effectiveUser");
  692   my @problemIDs = sort { $a <=> $b } $db->listUserProblems($eUserID, $setID);
  693 
  694   print CGI::start_div({class=>"info-box", id=>"fisheye"});
  695   print CGI::h2("Problems");
  696   #print CGI::start_ul({class=>"LinksMenu"});
  697   #print CGI::start_li();
  698   #print CGI::span({style=>"font-size:larger"}, "Problems");
  699   print CGI::start_ul();
  700 
  701   foreach my $problemID (@problemIDs) {
  702     my $problemPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Problem",
  703       courseID => $courseID, setID => $setID, problemID => $problemID);
  704     print CGI::li(CGI::a( {href=>$self->systemLink($problemPage,
  705                           params=>{  displayMode => $self->{displayMode},
  706                                  showOldAnswers => $self->{will}->{showOldAnswers}
  707                               })},  "Problem $problemID")
  708      );
  709   }
  710 
  711   print CGI::end_ul();
  712   #print CGI::end_li();
  713   #print CGI::end_ul();
  714   print CGI::end_div();
  715 
  716   return "";
  717 }
  718 
  719 sub nav {
  720   my ($self, $args) = @_;
  721   my $r = $self->r;
  722   my $db = $r->db;
  723   my $urlpath = $r->urlpath;
  724 
  725   return "" if ( $self->{invalidSet} );
  726 
  727   my $courseID = $urlpath->arg("courseID");
  728   my $setID = $self->{set}->set_id if !($self->{invalidSet});
  729   my $problemID = $self->{problem}->problem_id if !($self->{invalidProblem});
  730   my $eUserID = $r->param("effectiveUser");
  731 
  732   my ($prevID, $nextID);
  733 
  734   if (!$self->{invalidProblem}) {
  735     my @problemIDs = $db->listUserProblems($eUserID, $setID);
  736     foreach my $id (@problemIDs) {
  737       $prevID = $id if $id < $problemID
  738         and (not defined $prevID or $id > $prevID);
  739       $nextID = $id if $id > $problemID
  740         and (not defined $nextID or $id < $nextID);
  741     }
  742   }
  743 
  744   my @links;
  745 
  746   if ($prevID) {
  747     my $prevPage = $urlpath->newFromModule(__PACKAGE__,
  748       courseID => $courseID, setID => $setID, problemID => $prevID);
  749     push @links, "Previous Problem", $r->location . $prevPage->path, "navPrev";
  750   } else {
  751     push @links, "Previous Problem", "", "navPrevGrey";
  752   }
  753 
  754   if (defined($setID) && $setID ne 'Undefined_Set') {
  755     push @links, "Problem List", $r->location . $urlpath->parent->path, "navProbList";
  756   } else {
  757     push @links, "Problem List", "", "navProbListGrey";
  758   }
  759 
  760   if ($nextID) {
  761     my $nextPage = $urlpath->newFromModule(__PACKAGE__,
  762       courseID => $courseID, setID => $setID, problemID => $nextID);
  763     push @links, "Next Problem", $r->location . $nextPage->path, "navNext";
  764   } else {
  765     push @links, "Next Problem", "", "navNextGrey";
  766   }
  767 
  768   my $tail = "";
  769 
  770   $tail .= "&displayMode=".$self->{displayMode} if defined $self->{displayMode};
  771   $tail .= "&showOldAnswers=".$self->{will}->{showOldAnswers}
  772     if defined $self->{will}->{showOldAnswers};
  773   return $self->navMacro($args, $tail, @links);
  774 }
  775 
  776 sub title {
  777   my ($self) = @_;
  778 
  779   # using the url arguments won't break if the set/problem are invalid
  780   my $setID = WeBWorK::ContentGenerator::underscore2nbsp($self->r->urlpath->arg("setID"));
  781   my $problemID = $self->r->urlpath->arg("problemID");
  782 
  783   return "$setID: Problem $problemID";
  784 }
  785 
  786 sub body {
  787   my $self = shift;
  788   my $r = $self->r;
  789   my $ce = $r->ce;
  790   my $db = $r->db;
  791   my $authz = $r->authz;
  792   my $urlpath = $r->urlpath;
  793   my $user = $r->param('user');
  794   my $effectiveUser = $r->param('effectiveUser');
  795 
  796   if ( $self->{invalidSet} ) {
  797     return CGI::div({class=>"ResultsWithError"},
  798         CGI::p("The selected problem set (" .
  799                $urlpath->arg("setID") . ") is not " .
  800                "a valid set for $effectiveUser:"),
  801         CGI::p($self->{invalidSet}));
  802   }
  803 
  804   if ($self->{invalidProblem}) {
  805     return CGI::div({class=>"ResultsWithError"},
  806       CGI::p("The selected problem (" . $urlpath->arg("problemID") . ") is not a valid problem for set " . $self->{set}->set_id . "."));
  807   }
  808 
  809   # unpack some useful variables
  810   my $set             = $self->{set};
  811   my $problem         = $self->{problem};
  812   my $editMode        = $self->{editMode};
  813   my $submitAnswers   = $self->{submitAnswers};
  814   my $checkAnswers    = $self->{checkAnswers};
  815   my $previewAnswers  = $self->{previewAnswers};
  816   my %want            = %{ $self->{want} };
  817   my %can             = %{ $self->{can}  };
  818   my %must            = %{ $self->{must} };
  819   my %will            = %{ $self->{will} };
  820   my $pg              = $self->{pg};
  821 
  822   my $courseName = $urlpath->arg("courseID");
  823 
  824   # FIXME: move editor link to top, next to problem number.
  825   # format as "[edit]" like we're doing with course info file, etc.
  826   # add edit link for set as well.
  827   my $editorLink = "";
  828   # if we are here without a real homework set, carry that through
  829   my $forced_field = [];
  830   $forced_field = ['sourceFilePath' =>  $r->param("sourceFilePath")] if
  831     ($set->set_id eq 'Undefined_Set');
  832   if ($authz->hasPermissions($user, "modify_problem_sets")) {
  833     my $editorPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::PGProblemEditor",
  834       courseID => $courseName, setID => $set->set_id, problemID => $problem->problem_id);
  835     my $editorURL = $self->systemLink($editorPage, params=>$forced_field);
  836     $editorLink = CGI::p(CGI::a({href=>$editorURL,target =>'WW_Editor'}, "Edit this problem"));
  837   }
  838 
  839   ##### translation errors? #####
  840 
  841   if ($pg->{flags}->{error_flag}) {
  842     if ($authz->hasPermissions($user, "view_problem_debugging_info")) {
  843       print $self->errorOutput($pg->{errors}, $pg->{body_text});
  844     } else {
  845       print $self->errorOutput($pg->{errors}, "You do not have permission to view the details of this error.");
  846     }
  847     print $editorLink;
  848     return "";
  849   }
  850 
  851   ##### answer processing #####
  852   debug("begin answer processing");
  853   # if answers were submitted:
  854   my $scoreRecordedMessage;
  855   my $pureProblem;
  856   if ($submitAnswers) {
  857     # get a "pure" (unmerged) UserProblem to modify
  858     # this will be undefined if the problem has not been assigned to this user
  859     $pureProblem = $db->getUserProblem($problem->user_id, $problem->set_id, $problem->problem_id); # checked
  860     if (defined $pureProblem) {
  861       # store answers in DB for sticky answers
  862       my %answersToStore;
  863       my %answerHash = %{ $pg->{answers} };
  864       $answersToStore{$_} = $self->{formFields}->{$_}  #$answerHash{$_}->{original_student_ans} -- this may have been modified for fields with multiple values.  Don't use it!!
  865         foreach (keys %answerHash);
  866 
  867       # There may be some more answers to store -- one which are auxiliary entries to a primary answer.  Evaluating
  868       # matrices works in this way, only the first answer triggers an answer evaluator, the rest are just inputs
  869       # however we need to store them.  Fortunately they are still in the input form.
  870       my @extra_answer_names  = @{ $pg->{flags}->{KEPT_EXTRA_ANSWERS}};
  871       $answersToStore{$_} = $self->{formFields}->{$_} foreach  (@extra_answer_names);
  872 
  873       # Now let's encode these answers to store them -- append the extra answers to the end of answer entry order
  874       my @answer_order = (@{$pg->{flags}->{ANSWER_ENTRY_ORDER}}, @extra_answer_names);
  875       my $answerString = encodeAnswers(%answersToStore,
  876          @answer_order);
  877 
  878       # store last answer to database
  879       $problem->last_answer($answerString);
  880       $pureProblem->last_answer($answerString);
  881       $db->putUserProblem($pureProblem);
  882 
  883       # store state in DB if it makes sense
  884       if ($will{recordAnswers}) {
  885         $problem->status($pg->{state}->{recorded_score});
  886         $problem->sub_status($pg->{state}->{sub_recorded_score});
  887         $problem->attempted(1);
  888         $problem->num_correct($pg->{state}->{num_of_correct_ans});
  889         $problem->num_incorrect($pg->{state}->{num_of_incorrect_ans});
  890         $pureProblem->status($pg->{state}->{recorded_score});
  891         $pureProblem->sub_status($pg->{state}->{sub_recorded_score});
  892         $pureProblem->attempted(1);
  893         $pureProblem->num_correct($pg->{state}->{num_of_correct_ans});
  894         $pureProblem->num_incorrect($pg->{state}->{num_of_incorrect_ans});
  895         if ($db->putUserProblem($pureProblem)) {
  896           $scoreRecordedMessage = "Your score was recorded.";
  897         } else {
  898           $scoreRecordedMessage = "Your score was not recorded because there was a failure in storing the problem record to the database.";
  899         }
  900         # write to the transaction log, just to make sure
  901         writeLog($self->{ce}, "transaction",
  902           $problem->problem_id."\t".
  903           $problem->set_id."\t".
  904           $problem->user_id."\t".
  905           $problem->source_file."\t".
  906           $problem->value."\t".
  907           $problem->max_attempts."\t".
  908           $problem->problem_seed."\t".
  909           $pureProblem->status."\t".
  910           $pureProblem->attempted."\t".
  911           $pureProblem->last_answer."\t".
  912           $pureProblem->num_correct."\t".
  913           $pureProblem->num_incorrect
  914         );
  915       } else {
  916         if (before($set->open_date) or after($set->due_date)) {
  917           $scoreRecordedMessage = "Your score was not recorded because this homework set is closed.";
  918         } else {
  919           $scoreRecordedMessage = "Your score was not recorded.";
  920         }
  921       }
  922     } else {
  923       $scoreRecordedMessage = "Your score was not recorded because this problem has not been assigned to you.";
  924     }
  925   }
  926 
  927   # logging student answers
  928 
  929   my $answer_log    = $self->{ce}->{courseFiles}->{logs}->{'answer_log'};
  930   if ( defined($answer_log ) and defined($pureProblem)) {
  931     if ($submitAnswers && !$authz->hasPermissions($effectiveUser, "dont_log_past_answers")) {
  932             my $answerString = ""; my $scores = "";
  933       my %answerHash = %{ $pg->{answers} };
  934       # FIXME  this is the line 552 error.  make sure original student ans is defined.
  935       # The fact that it is not defined is probably due to an error in some answer evaluator.
  936       # But I think it is useful to suppress this error message in the log.
  937       foreach (sortByName(undef, keys %answerHash)) {
  938         my $orig_ans = $answerHash{$_}->{original_student_ans};
  939         my $student_ans = defined $orig_ans ? $orig_ans : '';
  940         $answerString  .= $student_ans."\t";
  941         $scores .= $answerHash{$_}->{score} >= 1 ? "1" : "0";
  942       }
  943       $answerString = '' unless defined($answerString); # insure string is defined.
  944       writeCourseLog($self->{ce}, "answer_log",
  945               join("",
  946             '|', $problem->user_id,
  947             '|', $problem->set_id,
  948             '|', $problem->problem_id,
  949             '|', $scores, "\t",
  950             time(),"\t",
  951             $answerString,
  952           ),
  953       );
  954 
  955     }
  956   }
  957 
  958   debug("end answer processing");
  959 
  960   ##### output #####
  961   # custom message for editor
  962   if ($authz->hasPermissions($user, "modify_problem_sets") and defined $editMode) {
  963     if ($editMode eq "temporaryFile") {
  964       print CGI::p(CGI::div({class=>'temporaryFile'}, "Viewing temporary file: ", $problem->source_file));
  965     } elsif ($editMode eq "savedFile") {
  966       # taken care of in the initialization phase
  967     }
  968   }
  969   print CGI::start_div({class=>"problemHeader"});
  970 
  971 
  972 
  973   # attempt summary
  974   #FIXME -- the following is a kludge:  if showPartialCorrectAnswers is negative don't show anything.
  975   # until after the due date
  976   # do I need to check $will{showCorrectAnswers} to make preflight work??
  977   if (($pg->{flags}->{showPartialCorrectAnswers} >= 0 and $submitAnswers) ) {
  978     # print this if user submitted answers OR requested correct answers
  979 
  980     print $self->attemptResults($pg, 1,
  981       $will{showCorrectAnswers},
  982       $pg->{flags}->{showPartialCorrectAnswers}, 1, 1);
  983   } elsif ($checkAnswers) {
  984     # print this if user previewed answers
  985     print CGI::div({class=>'ResultsWithError'},"ANSWERS ONLY CHECKED -- ANSWERS NOT RECORDED"), CGI::br();
  986     print $self->attemptResults($pg, 1, $will{showCorrectAnswers}, 1, 1, 1);
  987       # show attempt answers
  988       # show correct answers if asked
  989       # show attempt results (correctness)
  990       # show attempt previews
  991   } elsif ($previewAnswers) {
  992     # print this if user previewed answers
  993     print CGI::div({class=>'ResultsWithError'},"PREVIEW ONLY -- ANSWERS NOT RECORDED"),CGI::br(),$self->attemptResults($pg, 1, 0, 0, 0, 1);
  994       # show attempt answers
  995       # don't show correct answers
  996       # don't show attempt results (correctness)
  997       # show attempt previews
  998   }
  999 
 1000   print CGI::end_div();
 1001 
 1002   # main form
 1003   print "\n";
 1004   print CGI::start_form(-method=>"POST", -action=> $r->uri,-name=>"problemMainForm", onsubmit=>"submitAction()");
 1005   print $self->hidden_authen_fields;
 1006   print "\n";
 1007   print CGI::start_div({class=>"problem"});
 1008   print CGI::p($pg->{body_text});
 1009   print CGI::p(CGI::b("Note: "). CGI::i($pg->{result}->{msg})) if $pg->{result}->{msg};
 1010   print $editorLink; # this is empty unless it is appropriate to have an editor link.
 1011   print CGI::end_div();
 1012 
 1013   print CGI::start_p();
 1014 
 1015   if ($can{showCorrectAnswers}) {
 1016     print CGI::checkbox(
 1017       -name    => "showCorrectAnswers",
 1018       -checked => $will{showCorrectAnswers},
 1019       -label   => "Show correct answers",
 1020       -value   => 1,
 1021     );
 1022   }
 1023   if ($can{showHints}) {
 1024     print CGI::div({style=>"color:red"},
 1025       CGI::checkbox(
 1026         -name    => "showHints",
 1027         -checked => $will{showHints},
 1028         -label   => "Show Hints",
 1029         -value   =>1,
 1030       )
 1031     );
 1032   }
 1033   if ($can{showSolutions}) {
 1034     print CGI::checkbox(
 1035       -name    => "showSolutions",
 1036       -checked => $will{showSolutions},
 1037       -label   => "Show Solutions",
 1038       -value   => 1,
 1039     );
 1040   }
 1041 
 1042   if ($can{showCorrectAnswers} or $can{showHints} or $can{showSolutions}) {
 1043     print CGI::br();
 1044   }
 1045 
 1046   print CGI::submit(-name=>"previewAnswers", -label=>"Preview Answers");
 1047   if ($can{checkAnswers}) {
 1048     print CGI::submit(-name=>"checkAnswers", -label=>"Check Answers");
 1049   }
 1050   if ($can{getSubmitButton}) {
 1051     if ($user ne $effectiveUser) {
 1052       # if acting as a student, make it clear that answer submissions will
 1053       # apply to the student's records, not the professor's.
 1054       print CGI::submit(-name=>"submitAnswers", -label=>"Submit Answers for $effectiveUser");
 1055     } else {
 1056       #print CGI::submit(-name=>"submitAnswers", -label=>"Submit Answers", -onclick=>"alert('submit button clicked')");
 1057       print CGI::submit(-name=>"submitAnswers", -label=>"Submit Answers", -onclick=>"");
 1058       # FIXME  for unknown reasons the -onclick label seems to have to be there in order to allow the forms onsubmit to trigger
 1059       # WFT???
 1060     }
 1061   }
 1062 
 1063   print CGI::end_p();
 1064 
 1065   print CGI::start_div({class=>"scoreSummary"});
 1066 
 1067   # score summary
 1068   my $attempts = $problem->num_correct + $problem->num_incorrect;
 1069   my $attemptsNoun = $attempts != 1 ? "times" : "time";
 1070   my $problem_status    = $problem->status || 0;
 1071   my $lastScore = sprintf("%.0f%%", $problem_status * 100); # Round to whole number
 1072   my ($attemptsLeft, $attemptsLeftNoun);
 1073   if ($problem->max_attempts == -1) {
 1074     # unlimited attempts
 1075     $attemptsLeft = "unlimited";
 1076     $attemptsLeftNoun = "attempts";
 1077   } else {
 1078     $attemptsLeft = $problem->max_attempts - $attempts;
 1079     $attemptsLeftNoun = $attemptsLeft == 1 ? "attempt" : "attempts";
 1080   }
 1081 
 1082   my $setClosed = 0;
 1083   my $setClosedMessage;
 1084   if (before($set->open_date) or after($set->due_date)) {
 1085     $setClosed = 1;
 1086     if (before($set->open_date)) {
 1087       $setClosedMessage = "This homework set is not yet open.";
 1088     } elsif (after($set->due_date)) {
 1089       $setClosedMessage = "This homework set is closed.";
 1090     }
 1091   }
 1092   #if (before($set->open_date) or after($set->due_date)) {
 1093   # $setClosed = 1;
 1094   # $setClosedMessage = "This homework set is closed.";
 1095   # if ($authz->hasPermissions($user, "view_answers")) {
 1096   #   $setClosedMessage .= " However, since you are a privileged user, additional attempts will be recorded.";
 1097   # } else {
 1098   #   $setClosedMessage .= " Additional attempts will not be recorded.";
 1099   # }
 1100   #}
 1101   unless (defined( $pg->{state}->{state_summary_msg}) and $pg->{state}->{state_summary_msg}=~/\S/) {
 1102     my $notCountedMessage = ($problem->value) ? "" : "(This problem will not count towards your grade.)";
 1103     print CGI::p(join("",
 1104       $submitAnswers ? $scoreRecordedMessage . CGI::br() : "",
 1105       "You have attempted this problem $attempts $attemptsNoun.", CGI::br(),
 1106       $submitAnswers ?"You received a score of ".sprintf("%.0f%%", $pg->{result}->{score} * 100)." for this attempt.".CGI::br():'',
 1107       $problem->attempted
 1108         ? "Your overall recorded score is $lastScore.  $notCountedMessage" . CGI::br()
 1109         : "",
 1110       $setClosed ? $setClosedMessage : "You have $attemptsLeft $attemptsLeftNoun remaining."
 1111     ));
 1112   }else {
 1113     print CGI::p($pg->{state}->{state_summary_msg});
 1114   }
 1115   print CGI::end_div();
 1116 
 1117   # save state for viewOptions
 1118   print  CGI::hidden(
 1119          -name  => "showOldAnswers",
 1120          -value => $will{showOldAnswers}
 1121        ),
 1122 
 1123        CGI::hidden(
 1124          -name  => "displayMode",
 1125          -value => $self->{displayMode}
 1126        );
 1127   print( CGI::hidden(
 1128          -name    => 'editMode',
 1129          -value   => $self->{editMode},
 1130        )
 1131   ) if defined($self->{editMode}) and $self->{editMode} eq 'temporaryFile';
 1132 
 1133   # this is a security risk -- students can use this to find the source code for the problem
 1134 
 1135   my $permissionLevel = $db->getPermissionLevel($user)->permission;
 1136   my $professorPermissionLevel = $ce->{userRoles}->{professor};
 1137   print( CGI::hidden(
 1138           -name   => 'sourceFilePath',
 1139           -value  =>  $self->{problem}->{source_file}
 1140   ))  if defined($self->{problem}->{source_file}) and $permissionLevel>= $professorPermissionLevel; # only allow this for professors
 1141 
 1142   print( CGI::hidden(
 1143           -name   => 'problemSeed',
 1144           -value  =>  $r->param("problemSeed")
 1145   ))  if defined($r->param("problemSeed")) and $permissionLevel>= $professorPermissionLevel; # only allow this for professors
 1146 
 1147 
 1148   # end of main form
 1149   print CGI::endform();
 1150 
 1151   print  CGI::start_div({class=>"problemFooter"});
 1152 
 1153   ## arguments for answer inspection button
 1154   #my $prof_url = $ce->{webworkURLs}->{oldProf};
 1155   #my $webworkURL = $ce->{webworkURLs}->{root};
 1156   #my $cgi_url = $prof_url;
 1157   #$cgi_url=~ s|/[^/]*$||;  # clip profLogin.pl
 1158   #my $authen_args = $self->url_authen_args();
 1159   #my $showPastAnswersURL = "$webworkURL/$courseName/instructor/show_answers/";
 1160 
 1161   my $pastAnswersPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::ShowAnswers",
 1162     courseID => $courseName);
 1163   my $showPastAnswersURL = $self->systemLink($pastAnswersPage, authen => 0); # no authen info for form action
 1164 
 1165   # print answer inspection button
 1166   if ($authz->hasPermissions($user, "view_answers")) {
 1167     print "\n",
 1168       CGI::start_form(-method=>"POST",-action=>$showPastAnswersURL,-target=>"WW_Info"),"\n",
 1169       $self->hidden_authen_fields,"\n",
 1170       CGI::hidden(-name => 'courseID',  -value=>$courseName), "\n",
 1171       CGI::hidden(-name => 'problemID', -value=>$problem->problem_id), "\n",
 1172       CGI::hidden(-name => 'setID',  -value=>$problem->set_id), "\n",
 1173       CGI::hidden(-name => 'studentUser',    -value=>$problem->user_id), "\n",
 1174       CGI::p( {-align=>"left"},
 1175         CGI::submit(-name => 'action',  -value=>'Show Past Answers')
 1176       ), "\n",
 1177       CGI::endform();
 1178   }
 1179 
 1180 
 1181   print $self->feedbackMacro(
 1182     module             => __PACKAGE__,
 1183     set                => $self->{set}->set_id,
 1184     problem            => $problem->problem_id,
 1185     displayMode        => $self->{displayMode},
 1186     showOldAnswers     => $will{showOldAnswers},
 1187     showCorrectAnswers => $will{showCorrectAnswers},
 1188     showHints          => $will{showHints},
 1189     showSolutions      => $will{showSolutions},
 1190     pg_object          => $pg,
 1191   );
 1192 
 1193   print CGI::end_div();
 1194 
 1195   # debugging stuff
 1196   if (0) {
 1197     print
 1198       CGI::hr(),
 1199       CGI::h2("debugging information"),
 1200       CGI::h3("form fields"),
 1201       ref2string($self->{formFields}),
 1202       CGI::h3("user object"),
 1203       ref2string($self->{user}),
 1204       CGI::h3("set object"),
 1205       ref2string($set),
 1206       CGI::h3("problem object"),
 1207       ref2string($problem),
 1208       CGI::h3("PG object"),
 1209       ref2string($pg, {'WeBWorK::PG::Translator' => 1});
 1210   }
 1211   debug("leaving body of Problem.pm");
 1212   return "";
 1213 }
 1214 
 1215 1;

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9