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

View of /trunk/webwork2/lib/WeBWorK/ContentGenerator/Problem.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3567 - (download) (as text) (annotate)
Thu Aug 25 00:58:21 2005 UTC (7 years, 8 months ago) by dpvc
File size: 44499 byte(s)
Avoid undefined due_date when problem is viewed from the library
browser.

    1 ################################################################################
    2 # WeBWorK Online Homework Delivery System
    3 # Copyright © 2000-2003 The WeBWorK Project, http://openwebwork.sf.net/
    4 # $CVSHeader: webwork-modperl/lib/WeBWorK/ContentGenerator/Problem.pm,v 1.181 2005/08/24 20:22:32 jj Exp $
    5 #
    6 # This program is free software; you can redistribute it and/or modify it under
    7 # the terms of either: (a) the GNU General Public License as published by the
    8 # Free Software Foundation; either version 2, or (at your option) any later
    9 # version, or (b) the "Artistic License" which comes with this package.
   10 #
   11 # This program is distributed in the hope that it will be useful, but WITHOUT
   12 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
   13 # FOR A PARTICULAR PURPOSE.  See either the GNU General Public License or the
   14 # Artistic License for more details.
   15 ################################################################################
   16 
   17 package WeBWorK::ContentGenerator::Problem;
   18 use base qw(WeBWorK::ContentGenerator);
   19 
   20 =head1 NAME
   21 
   22 WeBWorK::ContentGenerator::Problem - Allow a student to interact with a problem.
   23 
   24 =cut
   25 
   26 use strict;
   27 use warnings;
   28 use CGI qw();
   29 use File::Path qw(rmtree);
   30 use WeBWorK::Debug;
   31 use WeBWorK::Form;
   32 use WeBWorK::PG;
   33 use WeBWorK::PG::ImageGenerator;
   34 use WeBWorK::PG::IO;
   35 use WeBWorK::Utils qw(readFile writeLog writeCourseLog encodeAnswers decodeAnswers ref2string makeTempDirectory);
   36 use WeBWorK::DB::Utils qw(global2user user2global findDefaults);
   37 use URI::Escape;
   38 
   39 use WeBWorK::Utils::Tasks qw(fake_set fake_problem);
   40 
   41 ################################################################################
   42 # CGI param interface to this module (up-to-date as of v1.153)
   43 ################################################################################
   44 
   45 # Standard params:
   46 #
   47 #     user - user ID of real user
   48 #     key - session key
   49 #     effectiveUser - user ID of effective user
   50 #
   51 # Integration with PGProblemEditor:
   52 #
   53 #     editMode - if set, indicates alternate problem source location.
   54 #                can be "temporaryFile" or "savedFile".
   55 #
   56 #     sourceFilePath - path to file to be edited
   57 #     problemSeed - force problem seed to value
   58 #     success - success message to display
   59 #     failure - failure message to display
   60 #
   61 # Rendering options:
   62 #
   63 #     displayMode - name of display mode to use
   64 #
   65 #     showOldAnswers - request that last entered answer be shown (if allowed)
   66 #     showCorrectAnswers - request that correct answers be shown (if allowed)
   67 #     showHints - request that hints be shown (if allowed)
   68 #     showSolutions - request that solutions be shown (if allowed)
   69 #
   70 # Problem interaction:
   71 #
   72 #     AnSwEr# - answer blanks in problem
   73 #
   74 #     redisplay - name of the "Redisplay Problem" button
   75 #     submitAnswers - name of "Submit Answers" button
   76 #     checkAnswers - name of the "Check Answers" button
   77 #     previewAnswers - name of the "Preview Answers" button
   78 
   79 ################################################################################
   80 # "can" methods
   81 ################################################################################
   82 
   83 # Subroutines to determine if a user "can" perform an action. Each subroutine is
   84 # called with the following arguments:
   85 #
   86 #     ($self, $User, $EffectiveUser, $Set, $Problem)
   87 
   88 # Note that significant parts of the "can" methods are lifted into the
   89 # GatewayQuiz module.  It isn't direct, however, because of the necessity
   90 # of dealing with versioning there.
   91 
   92 sub can_showOldAnswers {
   93   #my ($self, $User, $EffectiveUser, $Set, $Problem) = @_;
   94 
   95   return 1;
   96 }
   97 
   98 sub can_showCorrectAnswers {
   99   my ($self, $User, $EffectiveUser, $Set, $Problem) = @_;
  100   my $authz = $self->r->authz;
  101 
  102   return
  103     after($Set->answer_date)
  104       ||
  105     $authz->hasPermissions($User->user_id, "show_correct_answers_before_answer_date")
  106     ;
  107 }
  108 
  109 sub can_showHints {
  110   #my ($self, $User, $EffectiveUser, $Set, $Problem) = @_;
  111 
  112   return 1;
  113 }
  114 
  115 sub can_showSolutions {
  116   my ($self, $User, $EffectiveUser, $Set, $Problem) = @_;
  117   my $authz = $self->r->authz;
  118 
  119   return
  120     after($Set->answer_date)
  121       ||
  122     $authz->hasPermissions($User->user_id, "show_solutions_before_answer_date")
  123     ;
  124 }
  125 
  126 sub can_recordAnswers {
  127   my ($self, $User, $EffectiveUser, $Set, $Problem, $submitAnswers) = @_;
  128   my $authz = $self->r->authz;
  129   my $thisAttempt = $submitAnswers ? 1 : 0;
  130   if ($User->user_id ne $EffectiveUser->user_id) {
  131     return $authz->hasPermissions($User->user_id, "record_answers_when_acting_as_student");
  132   }
  133   if (before($Set->open_date)) {
  134     return $authz->hasPermissions($User->user_id, "record_answers_before_open_date");
  135   } elsif (between($Set->open_date, $Set->due_date)) {
  136     my $max_attempts = $Problem->max_attempts;
  137     my $attempts_used = $Problem->num_correct + $Problem->num_incorrect + $thisAttempt;
  138     if ($max_attempts == -1 or $attempts_used < $max_attempts) {
  139       return $authz->hasPermissions($User->user_id, "record_answers_after_open_date_with_attempts");
  140     } else {
  141       return $authz->hasPermissions($User->user_id, "record_answers_after_open_date_without_attempts");
  142     }
  143   } elsif (between($Set->due_date, $Set->answer_date)) {
  144     return $authz->hasPermissions($User->user_id, "record_answers_after_due_date");
  145   } elsif (after($Set->answer_date)) {
  146     return $authz->hasPermissions($User->user_id, "record_answers_after_answer_date");
  147   }
  148 }
  149 
  150 sub can_checkAnswers {
  151   my ($self, $User, $EffectiveUser, $Set, $Problem, $submitAnswers) = @_;
  152   my $authz = $self->r->authz;
  153   my $thisAttempt = $submitAnswers ? 1 : 0;
  154 
  155   if (before($Set->open_date)) {
  156     return $authz->hasPermissions($User->user_id, "check_answers_before_open_date");
  157   } elsif (between($Set->open_date, $Set->due_date)) {
  158     my $max_attempts = $Problem->max_attempts;
  159     my $attempts_used = $Problem->num_correct + $Problem->num_incorrect + $thisAttempt;
  160     if ($max_attempts == -1 or $attempts_used < $max_attempts) {
  161       return $authz->hasPermissions($User->user_id, "check_answers_after_open_date_with_attempts");
  162     } else {
  163       return $authz->hasPermissions($User->user_id, "check_answers_after_open_date_without_attempts");
  164     }
  165   } elsif (between($Set->due_date, $Set->answer_date)) {
  166     return $authz->hasPermissions($User->user_id, "check_answers_after_due_date");
  167   } elsif (after($Set->answer_date)) {
  168     return $authz->hasPermissions($User->user_id, "check_answers_after_answer_date");
  169   }
  170 }
  171 
  172 # Helper functions for calculating times
  173 sub before  { return time <= $_[0] }
  174 sub after   { return time >= $_[0] }
  175 sub between { my $t = time; return $t > $_[0] && $t < $_[1] }
  176 
  177 # Reset the default in some cases
  178 sub set_showOldAnswers_default {
  179   my ($self, $ce, $userName, $authz, $set) = @_;
  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/;   # 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 above answer is correct.");
  283          } else {
  284            $summary .= CGI::div({class=>"ResultsWithError"},"The above answer is NOT ${fully}correct.");
  285          }
  286     } else {
  287         if ($numCorrect == scalar @answerNames) {
  288           $summary .= CGI::div({class=>"ResultsWithoutError"},"All of the above answers are correct.");
  289          }
  290          unless ($numCorrect + $numBlanks == scalar( @answerNames)) {
  291           $summary .= CGI::div({class=>"ResultsWithError"},"At least one of the above answers 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=>'emphasis'},$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     return '<SPAN CLASS="math">\\displaystyle{'.$tex.'}</SPAN>';
  370   }
  371 }
  372 
  373 ################################################################################
  374 # Template escape implementations
  375 ################################################################################
  376 
  377 sub pre_header_initialize {
  378   my ($self) = @_;
  379   my $r = $self->r;
  380   my $ce = $r->ce;
  381   my $db = $r->db;
  382   my $authz = $r->authz;
  383   my $urlpath = $r->urlpath;
  384 
  385   my $setName = $urlpath->arg("setID");
  386   my $problemNumber = $r->urlpath->arg("problemID");
  387   my $userName = $r->param('user');
  388   my $effectiveUserName = $r->param('effectiveUser');
  389   my $key = $r->param('key');
  390 
  391   my $user = $db->getUser($userName); # checked
  392   die "record for user $userName (real user) does not exist."
  393     unless defined $user;
  394 
  395   my $effectiveUser = $db->getUser($effectiveUserName); # checked
  396   die "record for user $effectiveUserName (effective user) does not exist."
  397     unless defined $effectiveUser;
  398 
  399   # obtain the merged set for $effectiveUser
  400   my $set = $db->getMergedSet($effectiveUserName, $setName); # checked
  401 
  402   $self->set_showOldAnswers_default($ce, $userName, $authz, $set);
  403 
  404 # gateway check here: we want to be sure that someone isn't trying to take
  405 # a GatewayQuiz through the regular problem/homework mechanism, thereby
  406 # circumventing the versioning, time limits, etc.
  407   die('Invalid access attempt: the Problem ContentGenerator was called ' .
  408       'for a GatewayQuiz assignment.')
  409       if ( defined($set) && defined( $set->assignment_type() ) &&
  410      $set->assignment_type() =~ /gateway/ );
  411 
  412   # Database fix (in case of undefined published values)
  413   # this is only necessary because some people keep holding to ww1.9 which did not have a published field
  414   # make sure published is set to 0 or 1
  415   if ( $set and $set->published ne "0" and $set->published ne "1") {
  416     my $globalSet = $db->getGlobalSet($set->set_id);
  417     $globalSet->published("1"); # defaults to published
  418     $db->putGlobalSet($globalSet);
  419     $set = $db->getMergedSet($effectiveUserName, $setName);
  420   } else {
  421     # don't do anything just yet, maybe we're a professor and we're
  422     # fabricating a set or haven't assigned it to ourselves just yet
  423   }
  424 
  425   # obtain the merged problem for $effectiveUser
  426   my $problem = $db->getMergedProblem($effectiveUserName, $setName, $problemNumber); # checked
  427 
  428   my $editMode = $r->param("editMode");
  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         # These are problems from setmaker.  If declared invalid, they won't come up
  460         $self->{invalidProblem} = $self->{invalidSet} = 1 unless defined $sourceFilePath;
  461 #       die "Problem $problemNumber in set $setName does not exist" unless defined $sourceFilePath;
  462         $problem = fake_problem($db);
  463         $problem->problem_id(1);
  464         $problem->source_file($sourceFilePath);
  465         $problem->user_id($effectiveUserName);
  466       } else {
  467         $problem = global2user($userProblemClass, $globalProblem);
  468         $problem->user_id($effectiveUserName);
  469         $problem->problem_seed(0);
  470         $problem->status(0);
  471         $problem->attempted(0);
  472         $problem->last_answer("");
  473         $problem->num_correct(0);
  474         $problem->num_incorrect(0);
  475       }
  476     }
  477 
  478     # now we're sure we have valid UserSet and UserProblem objects
  479     # yay!
  480 
  481     # now deal with possible editor overrides:
  482 
  483     # if the caller is asking to override the source file, and
  484     # editMode calls for a temporary file, do so
  485     my $sourceFilePath = $r->param("sourceFilePath");
  486     if (defined $sourceFilePath and
  487         (not defined $editMode or $editMode eq "temporaryFile")) {
  488       $problem->source_file($sourceFilePath);
  489     }
  490 
  491     # if the problem does not have a source file or no source file has been passed in
  492     # then this is really an invalid problem (probably from a bad URL)
  493     $self->{invalidProblem} = not (defined $sourceFilePath or $problem->source_file);
  494 
  495     # if the caller is asking to override the problem seed, do so
  496     my $problemSeed = $r->param("problemSeed");
  497     if (defined $problemSeed) {
  498       $problem->problem_seed($problemSeed);
  499     }
  500 
  501     my $publishedClass = ($set->published) ? "Published" : "Unpublished";
  502     my $publishedText = ($set->published) ? "visible to students." : "hidden from students.";
  503     $self->addmessage(CGI::p("This set is " . CGI::font({class=>$publishedClass}, $publishedText)));
  504 
  505   # test for additional set validity if it's not already invalid
  506         } else {
  507     # A set is valid if it exists and if it is either published or the user is privileged.
  508     $self->{invalidSet} = !(defined $set and ($set->published || $authz->hasPermissions($userName, "view_unpublished_sets")));
  509     $self->{invalidProblem} = !(defined $problem and ($set->published || $authz->hasPermissions($userName, "view_unpublished_sets")));
  510 
  511     $self->addbadmessage(CGI::p("This problem will not count towards your grade.")) if $problem and not $problem->value and not $self->{invalidProblem};
  512   }
  513 
  514   $self->{userName}          = $userName;
  515   $self->{effectiveUserName} = $effectiveUserName;
  516   $self->{user}              = $user;
  517   $self->{effectiveUser}     = $effectiveUser;
  518   $self->{set}               = $set;
  519   $self->{problem}           = $problem;
  520   $self->{editMode}          = $editMode;
  521 
  522   ##### form processing #####
  523 
  524   # set options from form fields (see comment at top of file for names)
  525   my $displayMode        = $r->param("displayMode") || $ce->{pg}->{options}->{displayMode};
  526   my $redisplay          = $r->param("redisplay");
  527   my $submitAnswers      = $r->param("submitAnswers");
  528   my $checkAnswers       = $r->param("checkAnswers");
  529   my $previewAnswers     = $r->param("previewAnswers");
  530 
  531   my $formFields = { WeBWorK::Form->new_from_paramable($r)->Vars };
  532 
  533   $self->{displayMode}    = $displayMode;
  534   $self->{redisplay}      = $redisplay;
  535   $self->{submitAnswers}  = $submitAnswers;
  536   $self->{checkAnswers}   = $checkAnswers;
  537   $self->{previewAnswers} = $previewAnswers;
  538   $self->{formFields}     = $formFields;
  539 
  540   # get result and send to message
  541   my $status_message = $r->param("status_message");
  542   $self->addmessage(CGI::p("$status_message")) if $status_message;
  543 
  544   # now that we've set all the necessary variables quit out if the set or problem is invalid
  545   return if $self->{invalidSet} || $self->{invalidProblem};
  546 
  547   ##### permissions #####
  548 
  549   # are we allowed to view this problem?
  550   $self->{isOpen} = after($set->open_date) || $authz->hasPermissions($userName, "view_unopened_sets");
  551   return unless $self->{isOpen};
  552 
  553   # what does the user want to do?
  554   #FIXME  There is a problem with checkboxes -- if they are not checked they are invisible.  Hence if the default mode in $ce is 1
  555   # there is no way to override this.  Probably this is ok for the last three options, but it was definitely not ok for showing
  556   # saved answers which is normally on, but you want to be able to turn it off!  This section should be moved to ContentGenerator
  557   # so that you can set these options anywhere.  We also need mechanisms for making them sticky.
  558   # Note: ProblemSet and ProblemSets might set showOldAnswers to '', which
  559   #       needs to be treated as if it is not set.
  560   my %want = (
  561     showOldAnswers     => (defined($r->param("showOldAnswers")) and $r->param("showOldAnswers") ne '') ? $r->param("showOldAnswers")  : $ce->{pg}->{options}->{showOldAnswers},
  562     showCorrectAnswers => $r->param("showCorrectAnswers") || $ce->{pg}->{options}->{showCorrectAnswers},
  563     showHints          => $r->param("showHints")          || $ce->{pg}->{options}->{showHints},
  564     showSolutions      => $r->param("showSolutions")      || $ce->{pg}->{options}->{showSolutions},
  565     recordAnswers      => $submitAnswers,
  566     checkAnswers       => $checkAnswers,
  567     getSubmitButton    => 1,
  568   );
  569 
  570   # are certain options enforced?
  571   my %must = (
  572     showOldAnswers     => 0,
  573     showCorrectAnswers => 0,
  574     showHints          => 0,
  575     showSolutions      => 0,
  576     recordAnswers      => ! $authz->hasPermissions($userName, "avoid_recording_answers"),
  577     checkAnswers       => 0,
  578     getSubmitButton    => 0,
  579   );
  580 
  581   # does the user have permission to use certain options?
  582   my @args = ($user, $effectiveUser, $set, $problem);
  583   my %can = (
  584     showOldAnswers     => $self->can_showOldAnswers(@args),
  585     showCorrectAnswers => $self->can_showCorrectAnswers(@args),
  586     showHints          => $self->can_showHints(@args),
  587     showSolutions      => $self->can_showSolutions(@args),
  588     recordAnswers      => $self->can_recordAnswers(@args, 0),
  589     checkAnswers       => $self->can_checkAnswers(@args, $submitAnswers),
  590     getSubmitButton    => $self->can_recordAnswers(@args, $submitAnswers),
  591   );
  592 
  593   # final values for options
  594   my %will;
  595   foreach (keys %must) {
  596     $will{$_} = $can{$_} && ($want{$_} || $must{$_});
  597   }
  598 
  599   ##### sticky answers #####
  600 
  601   if (not ($submitAnswers or $previewAnswers or $checkAnswers) and $will{showOldAnswers}) {
  602     # do this only if new answers are NOT being submitted
  603     my %oldAnswers = decodeAnswers($problem->last_answer);
  604     $formFields->{$_} = $oldAnswers{$_} foreach keys %oldAnswers;
  605   }
  606 
  607   ##### translation #####
  608 
  609   debug("begin pg processing");
  610   my $pg = WeBWorK::PG->new(
  611     $ce,
  612     $effectiveUser,
  613     $key,
  614     $set,
  615     $problem,
  616     $set->psvn, # FIXME: this field should be removed
  617     $formFields,
  618     { # translation options
  619       displayMode     => $displayMode,
  620       showHints       => $will{showHints},
  621       showSolutions   => $will{showSolutions},
  622       refreshMath2img => $will{showHints} || $will{showSolutions},
  623       processAnswers  => 1,
  624     },
  625   );
  626 
  627   debug("end pg processing");
  628 
  629   ##### fix hint/solution options #####
  630 
  631   $can{showHints}     &&= $pg->{flags}->{hintExists}
  632                       &&= $pg->{flags}->{showHintLimit}<=$pg->{state}->{num_of_incorrect_ans};
  633   $can{showSolutions} &&= $pg->{flags}->{solutionExists};
  634 
  635   ##### store fields #####
  636 
  637   $self->{want} = \%want;
  638   $self->{must} = \%must;
  639   $self->{can}  = \%can;
  640   $self->{will} = \%will;
  641   $self->{pg} = $pg;
  642 }
  643 
  644 sub if_errors($$) {
  645   my ($self, $arg) = @_;
  646 
  647   if ($self->{isOpen}) {
  648     return $self->{pg}->{flags}->{error_flag} ? $arg : !$arg;
  649   } else {
  650     return !$arg;
  651   }
  652 }
  653 
  654 sub head {
  655   my ($self) = @_;
  656 
  657   return "" unless $self->{isOpen};
  658   return $self->{pg}->{head_text} if $self->{pg}->{head_text};
  659 }
  660 
  661 sub options {
  662   my ($self) = @_;
  663   #warn "doing options in Problem";
  664 
  665   # don't show options if we don't have anything to show
  666   return if $self->{invalidSet} or $self->{invalidProblem};
  667   return unless $self->{isOpen};
  668 
  669   my $displayMode = $self->{displayMode};
  670   my %can = %{ $self->{can} };
  671 
  672   my @options_to_show = "displayMode";
  673   push @options_to_show, "showOldAnswers" if $can{showOldAnswers};
  674   push @options_to_show, "showHints" if $can{showHints};
  675   push @options_to_show, "showSolutions" if $can{showSolutions};
  676 
  677   return $self->optionsMacro(
  678     options_to_show => \@options_to_show,
  679     extra_params => ["editMode", "sourceFilePath"],
  680   );
  681 }
  682 
  683 sub siblings {
  684   my ($self) = @_;
  685   my $r = $self->r;
  686   my $db = $r->db;
  687   my $urlpath = $r->urlpath;
  688 
  689   # can't show sibling problems if the set is invalid
  690   return "" if $self->{invalidSet};
  691 
  692   my $courseID = $urlpath->arg("courseID");
  693   my $setID = $self->{set}->set_id;
  694   my $eUserID = $r->param("effectiveUser");
  695   my @problemIDs = sort { $a <=> $b } $db->listUserProblems($eUserID, $setID);
  696 
  697   print CGI::start_ul({class=>"LinksMenu"});
  698   print CGI::start_li();
  699   print CGI::span({style=>"font-size:larger"}, "Problems");
  700   print CGI::start_ul();
  701 
  702   foreach my $problemID (@problemIDs) {
  703     my $problemPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Problem",
  704       courseID => $courseID, setID => $setID, problemID => $problemID);
  705     print CGI::li(CGI::a( {href=>$self->systemLink($problemPage,
  706                           params=>{  displayMode => $self->{displayMode},
  707                                  showOldAnswers => $self->{will}->{showOldAnswers}
  708                               })},  "Problem $problemID")
  709      );
  710   }
  711 
  712   print CGI::end_ul();
  713   print CGI::end_li();
  714   print CGI::end_ul();
  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   my $courseID = $urlpath->arg("courseID");
  726   my $setID = $self->{set}->set_id if !($self->{invalidSet});
  727   my $problemID = $self->{problem}->problem_id if !($self->{invalidProblem});
  728   my $eUserID = $r->param("effectiveUser");
  729 
  730   my ($prevID, $nextID);
  731 
  732   if (!$self->{invalidProblem}) {
  733     my @problemIDs = $db->listUserProblems($eUserID, $setID);
  734     foreach my $id (@problemIDs) {
  735       $prevID = $id if $id < $problemID
  736         and (not defined $prevID or $id > $prevID);
  737       $nextID = $id if $id > $problemID
  738         and (not defined $nextID or $id < $nextID);
  739     }
  740   }
  741 
  742   my @links;
  743 
  744   if ($prevID) {
  745     my $prevPage = $urlpath->newFromModule(__PACKAGE__,
  746       courseID => $courseID, setID => $setID, problemID => $prevID);
  747     push @links, "Previous Problem", $r->location . $prevPage->path, "navPrev";
  748   } else {
  749     push @links, "Previous Problem", "", "navPrev";
  750   }
  751 
  752   push @links, "Problem List", $r->location . $urlpath->parent->path, "navProbList";
  753 
  754   if ($nextID) {
  755     my $nextPage = $urlpath->newFromModule(__PACKAGE__,
  756       courseID => $courseID, setID => $setID, problemID => $nextID);
  757     push @links, "Next Problem", $r->location . $nextPage->path, "navNext";
  758   } else {
  759     push @links, "Next Problem", "", "navNext";
  760   }
  761 
  762   my $tail = "&displayMode=".$self->{displayMode}."&showOldAnswers=".$self->{will}->{showOldAnswers};
  763   return $self->navMacro($args, $tail, @links);
  764 }
  765 
  766 sub title {
  767   my ($self) = @_;
  768 
  769   # using the url arguments won't break if the set/problem are invalid
  770   my $setID = WeBWorK::ContentGenerator::underscore2nbsp($self->r->urlpath->arg("setID"));
  771   my $problemID = $self->r->urlpath->arg("problemID");
  772 
  773   return "$setID: Problem $problemID";
  774 }
  775 
  776 sub body {
  777   my $self = shift;
  778   my $r = $self->r;
  779   my $ce = $r->ce;
  780   my $db = $r->db;
  781   my $authz = $r->authz;
  782   my $urlpath = $r->urlpath;
  783   my $user = $r->param('user');
  784   my $effectiveUser = $r->param('effectiveUser');
  785 
  786   if ($self->{invalidSet}) {
  787     return CGI::div({class=>"ResultsWithError"},
  788       CGI::p("The selected homework set (" . $urlpath->arg("setID") . ") is not a valid set for " . $r->param("effectiveUser") . "."));
  789   }
  790 
  791   if ($self->{invalidProblem}) {
  792     return CGI::div({class=>"ResultsWithError"},
  793       CGI::p("The selected problem (" . $urlpath->arg("problemID") . ") is not a valid problem for set " . $self->{set}->set_id . "."));
  794   }
  795 
  796   unless ($self->{isOpen}) {
  797     return CGI::div({class=>"ResultsWithError"},
  798       CGI::p("This problem is not available because the homework set that contains it is not yet open."));
  799   }
  800   # unpack some useful variables
  801   my $set             = $self->{set};
  802   my $problem         = $self->{problem};
  803   my $editMode        = $self->{editMode};
  804   my $submitAnswers   = $self->{submitAnswers};
  805   my $checkAnswers    = $self->{checkAnswers};
  806   my $previewAnswers  = $self->{previewAnswers};
  807   my %want            = %{ $self->{want} };
  808   my %can             = %{ $self->{can}  };
  809   my %must            = %{ $self->{must} };
  810   my %will            = %{ $self->{will} };
  811   my $pg              = $self->{pg};
  812 
  813   my $courseName = $urlpath->arg("courseID");
  814 
  815   # FIXME: move editor link to top, next to problem number.
  816   # format as "[edit]" like we're doing with course info file, etc.
  817   # add edit link for set as well.
  818   my $editorLink = "";
  819   # if we are here without a real problem set, carry that through
  820   my $forced_field = [];
  821   $forced_field = ['sourceFilePath' =>  $r->param("sourceFilePath")] if
  822     ($set->set_id eq 'Undefined_Set');
  823   if ($authz->hasPermissions($user, "modify_problem_sets")) {
  824     my $editorPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::PGProblemEditor",
  825       courseID => $courseName, setID => $set->set_id, problemID => $problem->problem_id);
  826     my $editorURL = $self->systemLink($editorPage, params=>$forced_field);
  827     $editorLink = CGI::a({href=>$editorURL}, "Edit this problem");
  828   }
  829 
  830   ##### translation errors? #####
  831 
  832   if ($pg->{flags}->{error_flag}) {
  833     print $self->errorOutput($pg->{errors}, $pg->{body_text});
  834     print $editorLink;
  835     return "";
  836   }
  837 
  838   ##### answer processing #####
  839   debug("begin answer processing");
  840   # if answers were submitted:
  841   my $scoreRecordedMessage;
  842   my $pureProblem;
  843   if ($submitAnswers) {
  844     # get a "pure" (unmerged) UserProblem to modify
  845     # this will be undefined if the problem has not been assigned to this user
  846     $pureProblem = $db->getUserProblem($problem->user_id, $problem->set_id, $problem->problem_id); # checked
  847     if (defined $pureProblem) {
  848       # store answers in DB for sticky answers
  849       my %answersToStore;
  850       my %answerHash = %{ $pg->{answers} };
  851       $answersToStore{$_} = $self->{formFields}->{$_}  #$answerHash{$_}->{original_student_ans} -- this may have been modified for fields with multiple values.  Don't use it!!
  852         foreach (keys %answerHash);
  853 
  854       # There may be some more answers to store -- one which are auxiliary entries to a primary answer.  Evaluating
  855       # matrices works in this way, only the first answer triggers an answer evaluator, the rest are just inputs
  856       # however we need to store them.  Fortunately they are still in the input form.
  857       my @extra_answer_names  = @{ $pg->{flags}->{KEPT_EXTRA_ANSWERS}};
  858       $answersToStore{$_} = $self->{formFields}->{$_} foreach  (@extra_answer_names);
  859 
  860       # Now let's encode these answers to store them -- append the extra answers to the end of answer entry order
  861       my @answer_order = (@{$pg->{flags}->{ANSWER_ENTRY_ORDER}}, @extra_answer_names);
  862       my $answerString = encodeAnswers(%answersToStore,
  863          @answer_order);
  864 
  865       # store last answer to database
  866       $problem->last_answer($answerString);
  867       $pureProblem->last_answer($answerString);
  868       $db->putUserProblem($pureProblem);
  869 
  870       # store state in DB if it makes sense
  871       if ($will{recordAnswers}) {
  872         $problem->status($pg->{state}->{recorded_score});
  873         $problem->attempted(1);
  874         $problem->num_correct($pg->{state}->{num_of_correct_ans});
  875         $problem->num_incorrect($pg->{state}->{num_of_incorrect_ans});
  876         $pureProblem->status($pg->{state}->{recorded_score});
  877         $pureProblem->attempted(1);
  878         $pureProblem->num_correct($pg->{state}->{num_of_correct_ans});
  879         $pureProblem->num_incorrect($pg->{state}->{num_of_incorrect_ans});
  880         if ($db->putUserProblem($pureProblem)) {
  881           $scoreRecordedMessage = "Your score was recorded.";
  882         } else {
  883           $scoreRecordedMessage = "Your score was not recorded because there was a failure in storing the problem record to the database.";
  884         }
  885         # write to the transaction log, just to make sure
  886         writeLog($self->{ce}, "transaction",
  887           $problem->problem_id."\t".
  888           $problem->set_id."\t".
  889           $problem->user_id."\t".
  890           $problem->source_file."\t".
  891           $problem->value."\t".
  892           $problem->max_attempts."\t".
  893           $problem->problem_seed."\t".
  894           $pureProblem->status."\t".
  895           $pureProblem->attempted."\t".
  896           $pureProblem->last_answer."\t".
  897           $pureProblem->num_correct."\t".
  898           $pureProblem->num_incorrect
  899         );
  900       } else {
  901         if (before($set->open_date) or after($set->due_date)) {
  902           $scoreRecordedMessage = "Your score was not recorded because this homework set is closed.";
  903         } else {
  904           $scoreRecordedMessage = "Your score was not recorded.";
  905         }
  906       }
  907     } else {
  908       $scoreRecordedMessage = "Your score was not recorded because this problem has not been assigned to you.";
  909     }
  910   }
  911 
  912   # logging student answers
  913 
  914   my $answer_log    = $self->{ce}->{courseFiles}->{logs}->{'answer_log'};
  915   if ( defined($answer_log ) and defined($pureProblem)) {
  916     if ($submitAnswers && !$authz->hasPermissions($effectiveUser, "dont_log_past_answers")) {
  917             my $answerString = ""; my $scores = "";
  918       my %answerHash = %{ $pg->{answers} };
  919       # FIXME  this is the line 552 error.  make sure original student ans is defined.
  920       # The fact that it is not defined is probably due to an error in some answer evaluator.
  921       # But I think it is useful to suppress this error message in the log.
  922       foreach (sort keys %answerHash) {
  923         my $orig_ans = $answerHash{$_}->{original_student_ans};
  924         my $student_ans = defined $orig_ans ? $orig_ans : '';
  925         $answerString  .= $student_ans."\t";
  926         $scores .= $answerHash{$_}->{score} >= 1 ? "1" : "0";
  927       }
  928       $answerString = '' unless defined($answerString); # insure string is defined.
  929       writeCourseLog($self->{ce}, "answer_log",
  930               join("",
  931             '|', $problem->user_id,
  932             '|', $problem->set_id,
  933             '|', $problem->problem_id,
  934             '|', $scores, "\t",
  935             time(),"\t",
  936             $answerString,
  937           ),
  938       );
  939 
  940     }
  941   }
  942 
  943   debug("end answer processing");
  944 
  945   ##### output #####
  946   # custom message for editor
  947   if ($authz->hasPermissions($user, "modify_problem_sets") and defined $editMode) {
  948     if ($editMode eq "temporaryFile") {
  949       print CGI::p(CGI::div({class=>'temporaryFile'}, "Viewing temporary file: ", $problem->source_file));
  950     } elsif ($editMode eq "savedFile") {
  951       # taken care of in the initialization phase
  952     }
  953   }
  954   print CGI::start_div({class=>"problemHeader"});
  955 
  956 
  957 
  958   # attempt summary
  959   #FIXME -- the following is a kludge:  if showPartialCorrectAnswers is negative don't show anything.
  960   # until after the due date
  961   # do I need to check $will{showCorrectAnswers} to make preflight work??
  962   if (($pg->{flags}->{showPartialCorrectAnswers} >= 0 and $submitAnswers) ) {
  963     # print this if user submitted answers OR requested correct answers
  964 
  965     print $self->attemptResults($pg, 1,
  966       $will{showCorrectAnswers},
  967       $pg->{flags}->{showPartialCorrectAnswers}, 1, 1);
  968   } elsif ($checkAnswers) {
  969     # print this if user previewed answers
  970     print CGI::div({class=>'ResultsWithError'},"ANSWERS ONLY CHECKED -- ANSWERS NOT RECORDED"), CGI::br();
  971     print $self->attemptResults($pg, 1, $will{showCorrectAnswers}, 1, 1, 1);
  972       # show attempt answers
  973       # show correct answers if asked
  974       # show attempt results (correctness)
  975       # show attempt previews
  976   } elsif ($previewAnswers) {
  977     # print this if user previewed answers
  978     print CGI::div({class=>'ResultsWithError'},"PREVIEW ONLY -- ANSWERS NOT RECORDED"),CGI::br(),$self->attemptResults($pg, 1, 0, 0, 0, 1);
  979       # show attempt answers
  980       # don't show correct answers
  981       # don't show attempt results (correctness)
  982       # show attempt previews
  983   }
  984 
  985   print CGI::end_div();
  986 
  987   # main form
  988   print CGI::startform("POST", $r->uri);
  989   print $self->hidden_authen_fields;
  990 
  991   print CGI::start_div({class=>"problem"});
  992   print CGI::p($pg->{body_text});
  993   print CGI::p(CGI::b("Note: "), CGI::i($pg->{result}->{msg})) if $pg->{result}->{msg};
  994   print CGI::end_div();
  995 
  996   print CGI::start_p();
  997 
  998   if ($can{showCorrectAnswers}) {
  999     print CGI::checkbox(
 1000       -name    => "showCorrectAnswers",
 1001       -checked => $will{showCorrectAnswers},
 1002       -label   => "Show correct answers",
 1003     );
 1004   }
 1005   if ($can{showHints}) {
 1006     print CGI::div({style=>"color:red"},
 1007       CGI::checkbox(
 1008         -name    => "showHints",
 1009         -checked => $will{showHints},
 1010         -label   => "Show Hints",
 1011       )
 1012     );
 1013   }
 1014   if ($can{showSolutions}) {
 1015     print CGI::checkbox(
 1016       -name    => "showSolutions",
 1017       -checked => $will{showSolutions},
 1018       -label   => "Show Solutions",
 1019     );
 1020   }
 1021 
 1022   if ($can{showCorrectAnswers} or $can{showHints} or $can{showSolutions}) {
 1023     print CGI::br();
 1024   }
 1025 
 1026   print CGI::submit(-name=>"previewAnswers", -label=>"Preview Answers");
 1027   if ($can{checkAnswers}) {
 1028     print CGI::submit(-name=>"checkAnswers", -label=>"Check Answers");
 1029   }
 1030   if ($can{getSubmitButton}) {
 1031     if ($user ne $effectiveUser) {
 1032       # if acting as a student, make it clear that answer submissions will
 1033       # apply to the student's records, not the professor's.
 1034       print CGI::submit(-name=>"submitAnswers", -label=>"Submit Answers for $effectiveUser");
 1035     } else {
 1036       print CGI::submit(-name=>"submitAnswers", -label=>"Submit Answers");
 1037     }
 1038   }
 1039 
 1040   print CGI::end_p();
 1041 
 1042   print CGI::start_div({class=>"scoreSummary"});
 1043 
 1044   # score summary
 1045   my $attempts = $problem->num_correct + $problem->num_incorrect;
 1046   my $attemptsNoun = $attempts != 1 ? "times" : "time";
 1047   my $problem_status    = $problem->status || 0;
 1048   my $lastScore = sprintf("%.0f%%", $problem_status * 100); # Round to whole number
 1049   my ($attemptsLeft, $attemptsLeftNoun);
 1050   if ($problem->max_attempts == -1) {
 1051     # unlimited attempts
 1052     $attemptsLeft = "unlimited";
 1053     $attemptsLeftNoun = "attempts";
 1054   } else {
 1055     $attemptsLeft = $problem->max_attempts - $attempts;
 1056     $attemptsLeftNoun = $attemptsLeft == 1 ? "attempt" : "attempts";
 1057   }
 1058 
 1059   my $setClosed = 0;
 1060   my $setClosedMessage;
 1061   if (before($set->open_date) or after($set->due_date)) {
 1062     $setClosed = 1;
 1063     if (before($set->open_date)) {
 1064       $setClosedMessage = "This homework set is not yet open.";
 1065     } elsif (after($set->due_date)) {
 1066       $setClosedMessage = "This homework set is closed.";
 1067     }
 1068   }
 1069   #if (before($set->open_date) or after($set->due_date)) {
 1070   # $setClosed = 1;
 1071   # $setClosedMessage = "This homework set is closed.";
 1072   # if ($authz->hasPermissions($user, "view_answers")) {
 1073   #   $setClosedMessage .= " However, since you are a privileged user, additional attempts will be recorded.";
 1074   # } else {
 1075   #   $setClosedMessage .= " Additional attempts will not be recorded.";
 1076   # }
 1077   #}
 1078   unless (defined( $pg->{state}->{state_summary_msg}) and $pg->{state}->{state_summary_msg}=~/\S/) {
 1079     my $notCountedMessage = ($problem->value) ? "" : "(This problem will not count towards your grade.)";
 1080     print CGI::p(
 1081       $submitAnswers ? $scoreRecordedMessage . CGI::br() : "",
 1082       "You have attempted this problem $attempts $attemptsNoun.", CGI::br(),
 1083       $submitAnswers ?"You received a score of ".sprintf("%.0f%%", $pg->{result}->{score} * 100)." for this attempt.".CGI::br():'',
 1084       $problem->attempted
 1085         ? "Your overall recorded score is $lastScore.  $notCountedMessage" . CGI::br()
 1086         : "",
 1087       $setClosed ? $setClosedMessage : "You have $attemptsLeft $attemptsLeftNoun remaining."
 1088     );
 1089   }else {
 1090     print CGI::p($pg->{state}->{state_summary_msg});
 1091   }
 1092   print CGI::end_div();
 1093 
 1094   # save state for viewOptions
 1095   print  CGI::hidden(
 1096          -name  => "showOldAnswers",
 1097          -value => $will{showOldAnswers}
 1098        ),
 1099 
 1100        CGI::hidden(
 1101          -name  => "displayMode",
 1102          -value => $self->{displayMode}
 1103        );
 1104   print( CGI::hidden(
 1105          -name    => 'editMode',
 1106          -value   => $self->{editMode},
 1107        )
 1108   ) if defined($self->{editMode}) and $self->{editMode} eq 'temporaryFile';
 1109   print( CGI::hidden(
 1110           -name   => 'sourceFilePath',
 1111           -value  =>  $self->{problem}->{source_file}
 1112   ))  if defined($self->{problem}->{source_file});
 1113 
 1114   print( CGI::hidden(
 1115           -name   => 'problemSeed',
 1116           -value  =>  $r->param("problemSeed")
 1117   ))  if defined($r->param("problemSeed"));
 1118 
 1119   # end of main form
 1120   print CGI::endform();
 1121 
 1122   print  CGI::start_div({class=>"problemFooter"});
 1123 
 1124   ## arguments for answer inspection button
 1125   #my $prof_url = $ce->{webworkURLs}->{oldProf};
 1126   #my $webworkURL = $ce->{webworkURLs}->{root};
 1127   #my $cgi_url = $prof_url;
 1128   #$cgi_url=~ s|/[^/]*$||;  # clip profLogin.pl
 1129   #my $authen_args = $self->url_authen_args();
 1130   #my $showPastAnswersURL = "$webworkURL/$courseName/instructor/show_answers/";
 1131 
 1132   my $pastAnswersPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::ShowAnswers",
 1133     courseID => $courseName);
 1134   my $showPastAnswersURL = $self->systemLink($pastAnswersPage, authen => 0); # no authen info for form action
 1135 
 1136   # print answer inspection button
 1137   if ($authz->hasPermissions($user, "view_answers")) {
 1138     print "\n",
 1139       CGI::start_form(-method=>"POST",-action=>$showPastAnswersURL,-target=>"information"),"\n",
 1140       $self->hidden_authen_fields,"\n",
 1141       CGI::hidden(-name => 'courseID',  -value=>$courseName), "\n",
 1142       CGI::hidden(-name => 'problemID', -value=>$problem->problem_id), "\n",
 1143       CGI::hidden(-name => 'setID',  -value=>$problem->set_id), "\n",
 1144       CGI::hidden(-name => 'studentUser',    -value=>$problem->user_id), "\n",
 1145       CGI::p( {-align=>"left"},
 1146         CGI::submit(-name => 'action',  -value=>'Show Past Answers')
 1147       ), "\n",
 1148       CGI::endform();
 1149   }
 1150 
 1151   # feedback form url
 1152   my $feedbackPage = $urlpath->newFromModule("WeBWorK::ContentGenerator::Feedback",
 1153     courseID => $courseName);
 1154   my $feedbackURL = $self->systemLink($feedbackPage, authen => 0); # no authen info for form action
 1155 
 1156   #print feedback form
 1157   print
 1158     CGI::start_form(-method=>"POST", -action=>$feedbackURL),"\n",
 1159     $self->hidden_authen_fields,"\n",
 1160     CGI::hidden("module",             __PACKAGE__),"\n",
 1161     CGI::hidden("set",                $set->set_id),"\n",
 1162     CGI::hidden("problem",            $problem->problem_id),"\n",
 1163     CGI::hidden("displayMode",        $self->{displayMode}),"\n",
 1164     CGI::hidden("showOldAnswers",     $will{showOldAnswers}),"\n",
 1165     CGI::hidden("showCorrectAnswers", $will{showCorrectAnswers}),"\n",
 1166     CGI::hidden("showHints",          $will{showHints}),"\n",
 1167     CGI::hidden("showSolutions",      $will{showSolutions}),"\n",
 1168     CGI::p({-align=>"left"},
 1169       CGI::submit(-name=>"feedbackForm", -label=>"Email instructor")
 1170     ),
 1171     CGI::endform(),"\n";
 1172 
 1173   # FIXME print editor link
 1174   print $editorLink;   #empty unless it is appropriate to have an editor link.
 1175 
 1176   print CGI::end_div();
 1177 
 1178   # debugging stuff
 1179   if (0) {
 1180     print
 1181       CGI::hr(),
 1182       CGI::h2("debugging information"),
 1183       CGI::h3("form fields"),
 1184       ref2string($self->{formFields}),
 1185       CGI::h3("user object"),
 1186       ref2string($self->{user}),
 1187       CGI::h3("set object"),
 1188       ref2string($set),
 1189       CGI::h3("problem object"),
 1190       ref2string($problem),
 1191       CGI::h3("PG object"),
 1192       ref2string($pg, {'WeBWorK::PG::Translator' => 1});
 1193   }
 1194 
 1195   return "";
 1196 }
 1197 
 1198 1;

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9