File:  [LON-CAPA] / loncom / interface / statistics / lonstathelpers.pm
Revision 1.49: download - view: text, annotated - select for diffs
Fri Apr 8 13:35:50 2005 UTC (19 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: version_1_99_0_tmcc, HEAD
- I love <label>

    1: # The LearningOnline Network with CAPA
    2: #
    3: # $Id: lonstathelpers.pm,v 1.49 2005/04/08 13:35:50 albertel Exp $
    4: #
    5: # Copyright Michigan State University Board of Trustees
    6: #
    7: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    8: #
    9: # LON-CAPA is free software; you can redistribute it and/or modify
   10: # it under the terms of the GNU General Public License as published by
   11: # the Free Software Foundation; either version 2 of the License, or
   12: # (at your option) any later version.
   13: #
   14: # LON-CAPA is distributed in the hope that it will be useful,
   15: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   16: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   17: # GNU General Public License for more details.
   18: #
   19: # You should have received a copy of the GNU General Public License
   20: # along with LON-CAPA; if not, write to the Free Software
   21: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   22: #
   23: # /home/httpd/html/adm/gpl.txt
   24: #
   25: # http://www.lon-capa.org/
   26: #
   27: ####################################################
   28: ####################################################
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonstathelpers - helper routines used by statistics
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This module provides a place to consolidate much of the statistics 
   39: routines that are needed across multiple statistics functions.
   40: 
   41: =head1 OVERVIEW
   42: 
   43: =over 4
   44: 
   45: =cut
   46: 
   47: ####################################################
   48: ####################################################
   49: package Apache::lonstathelpers;
   50: 
   51: use strict;
   52: use Apache::lonnet;
   53: use Apache::loncommon();
   54: use Apache::lonhtmlcommon();
   55: use Apache::loncoursedata();
   56: use Apache::lonstatistics;
   57: use Apache::lonlocal;
   58: use HTML::Entities();
   59: use Time::Local();
   60: use Spreadsheet::WriteExcel();
   61: use GDBM_File;
   62: use Storable qw(freeze thaw);
   63: 
   64: ####################################################
   65: ####################################################
   66: 
   67: =pod
   68: 
   69: =item &render_resource($resource)
   70: 
   71: Input: a navmaps resource
   72: 
   73: Retunrs: a scalar containing html for a rendering of the problem
   74: within a table.
   75: 
   76: =cut
   77: 
   78: ####################################################
   79: ####################################################
   80: sub render_resource {
   81:     my ($resource) = @_;
   82:     ##
   83:     ## Render the problem
   84:     my ($base) = ($resource->src =~ m|^(.*/)[^/]*$|);
   85:     $base="http://".$ENV{'SERVER_NAME'}.$base;
   86:     my ($src,$symb)=($resource->src,&Apache::lonnet::escape($resource->symb));
   87:     my $rendered_problem = &Apache::lonnet::ssi_body($src.'?symb='.$symb);
   88:     $rendered_problem =~ s/<\s*form\s*/<nop /g;
   89:     $rendered_problem =~ s|(<\s*/form\s*>)|<\/nop>|g;
   90:     return '<table bgcolor="ffffff"><tr><td>'.
   91:         '<base href="'.$base.'" />'.
   92:         $rendered_problem.
   93:         '</td></tr></table>';
   94: }
   95: 
   96: ####################################################
   97: ####################################################
   98: 
   99: =pod
  100: 
  101: =item &get_resources
  102: 
  103: =cut
  104: 
  105: ####################################################
  106: ####################################################
  107: sub get_resources {
  108:     my ($navmap,$sequence) = @_;
  109:     my @resources = $navmap->retrieveResources($sequence,
  110:                                                sub { shift->is_problem(); },
  111:                                                0,0,0);
  112:     return @resources;
  113: }
  114: 
  115: ####################################################
  116: ####################################################
  117: 
  118: =pod
  119: 
  120: =item &problem_selector($AcceptedResponseTypes)
  121: 
  122: Input: scalar containing regular expression which matches response
  123: types to show.  '.' will yield all, '(option|radiobutton)' will match
  124: all option response and radiobutton problems.
  125: 
  126: Returns: A string containing html for a table which lists the sequences
  127: and their contents.  A radiobutton is provided for each problem.
  128: Skips 'survey' problems.
  129: 
  130: =cut
  131: 
  132: ####################################################
  133: ####################################################
  134: sub problem_selector {
  135:     my ($AcceptedResponseTypes) = @_;
  136:     my $Str;
  137:     $Str = "\n<table>\n";
  138:     my $rb_count =0;
  139:     my ($navmap,@sequences) = 
  140:         &Apache::lonstatistics::selected_sequences_with_assessments('all');
  141:     return $navmap if (! ref($navmap)); # error
  142:     foreach my $seq (@sequences) {
  143:         my $seq_str = '';
  144:         foreach my $res (&get_resources($navmap,$seq)) {
  145:             foreach my $part (@{$res->parts}) {
  146:                 my @response_ids   = $res->responseIds($part);
  147:                 my @response_types = $res->responseType($part);
  148:                 for (my $i=0;$i<scalar(@response_types);$i++){
  149:                     my $respid = $response_ids[$i];
  150:                     my $resptype = $response_types[$i];
  151:                     if ($resptype =~ m/$AcceptedResponseTypes/) {
  152:                         my $value = &make_target_id({symb=>$res->symb,
  153:                                                      part=>$part,
  154:                                                      respid=>$respid,
  155:                                                      resptype=>$resptype});
  156:                         my $checked = '';
  157:                         if ($env{'form.problemchoice'} eq $value) {
  158:                             $checked = 'checked ';
  159:                         }
  160:                         my $title = $res->compTitle;
  161:                         if (! defined($title) || $title eq '') {
  162:                             ($title) = ($res->src =~ m:/([^/]*)$:);
  163:                         }
  164:                         $seq_str .= '<tr>'.
  165:                             qq{<td><input type="radio" id="$rb_count" name="problemchoice" value="$value" $checked /></td>}.
  166:                             '<td><label for="'.$rb_count.'">'.$resptype.'</label></td>'.
  167:                             '<td><label for="'.$rb_count.'">'.$title.'</label>';
  168:                         if (scalar(@response_ids) > 1) {
  169:                             $seq_str .= &mt('response').' '.$respid;
  170:                         }
  171:                         my $link = $res->src.'?symb='.
  172:                             &Apache::lonnet::escape($res->symb);
  173:                         $seq_str .= ('&nbsp;'x2).
  174:                             qq{<a target="preview" href="$link">view</a>};
  175:                         $seq_str .= "</td></tr>\n";
  176:                         $rb_count++;
  177:                     }
  178:                 }
  179:             }
  180:         }
  181:         if ($seq_str ne '') {
  182:             $Str .= '<tr><td>&nbsp</td><td colspan="2"><b>'.$seq->compTitle.'</b></td>'.
  183:                 "</tr>\n".$seq_str;
  184:         }
  185:     }
  186:     $Str .= "</table>\n";
  187:     return $Str;
  188: }
  189: 
  190: ####################################################
  191: ####################################################
  192: 
  193: =pod
  194: 
  195: =item &MultipleProblemSelector($navmap,$selected,$inputname)
  196: 
  197: Generate HTML with checkboxes for problem selection.
  198: 
  199: Input: 
  200: 
  201: $navmap: a navmap object.  If undef, navmaps will be called to create a
  202: new object.
  203: 
  204: $selected: Scalar, Array, or hash reference of currently selected items.
  205: 
  206: $inputname: The name of the form elements to use for the checkboxs.
  207: 
  208: Returns: A string containing html for a table which lists the sequences
  209: and their contents.  A checkbox is provided for each problem.
  210: 
  211: =cut
  212: 
  213: ####################################################
  214: ####################################################
  215: sub MultipleProblemSelector {
  216:     my ($navmap,$inputname,$formname)=@_;
  217:     my $cid = $env{'request.course.id'};
  218:     my $Str;
  219:     # Massage the input as needed.
  220:     if (! defined($navmap)) {
  221:         $navmap = Apache::lonnavmaps::navmap->new();
  222:         if (! defined($navmap)) {
  223:             $Str .= 
  224:                 '<h1>'.&mt('Error: cannot process course structure').'</h1>';
  225:             return $Str;
  226:         }
  227:     }
  228:     my $selected = {map { ($_,1) } (&get_selected_symbs($inputname))};
  229:     # Header
  230:     $Str .= <<"END";
  231: <script language="JavaScript" type="text/javascript">
  232:     function checkall(value,seqid) {
  233:         for (i=0; i<document.forms.$formname.elements.length; i++) {
  234:             ele = document.forms.$formname.elements[i];
  235:             if (ele.name == '$inputname') {
  236:                 if (seqid != null) {
  237:                     itemid = document.forms.$formname.elements[i].id;
  238:                     thing = itemid.split(':');
  239:                     if (thing[0] == seqid) {
  240:                         document.forms.$formname.elements[i].checked=value;
  241:                     }
  242:                 } else {
  243:                     document.forms.$formname.elements[i].checked=value;
  244:                 }
  245:             }
  246:         }
  247:     }
  248: </script>
  249: END
  250:     $Str .= 
  251:         '<a href="javascript:checkall(true)">'.&mt('Select All').'</a>'.
  252:         ('&nbsp;'x4).
  253:         '<a href="javascript:checkall(false)">'.&mt('Unselect All').'</a>';
  254:     $Str .= $/.'<table>'.$/;
  255:     my $iterator = $navmap->getIterator(undef, undef, undef, 1);
  256:     my $sequence_string;
  257:     my $seq_id = 0;
  258:     my @Accumulator = (&new_accumulator($env{'course.'.$cid.'.description'},
  259:                                         '',
  260:                                         '',
  261:                                         $seq_id++,
  262:                                         $inputname));
  263:     my @Sequence_Data;
  264:     while (my $curRes = $iterator->next()) {
  265:         if ($curRes == $iterator->END_MAP) {
  266:             if (ref($Accumulator[-1]) eq 'CODE') {
  267:                 my $old_accumulator = pop(@Accumulator);
  268:                 push(@Sequence_Data,&{$old_accumulator}());
  269:             }
  270:         } elsif ($curRes == $iterator->BEGIN_MAP) {
  271:             # Not much to do here.
  272:         }
  273:         next if (! ref($curRes));
  274:         if ($curRes->is_map) {
  275:             push(@Accumulator,&new_accumulator($curRes->compTitle,
  276:                                                $curRes->src,
  277:                                                $curRes->symb,
  278:                                                $seq_id++,
  279:                                                $inputname));
  280:         } elsif ($curRes->is_problem) {
  281:             if (@Accumulator && $Accumulator[-1] ne '') {
  282:                 &{$Accumulator[-1]}($curRes,
  283:                                     exists($selected->{$curRes->symb}));
  284:             }
  285:         }
  286:     }
  287:     my $course_seq = pop(@Sequence_Data);
  288:     foreach my $seq ($course_seq,@Sequence_Data) {
  289:         #my $seq = pop(@Sequence_Data);
  290:         next if (! defined($seq) || ref($seq) ne 'HASH');
  291:         $Str.= '<tr><td colspan="2">'.
  292:             '<b>'.$seq->{'title'}.'</b>'.('&nbsp;'x2).
  293:             '<a href="javascript:checkall(true,'.$seq->{'id'}.')">'.
  294:                                   &mt('Select').'</a>'.('&nbsp;'x2).
  295:             '<a href="javascript:checkall(false,'.$seq->{'id'}.')">'.
  296:                                   &mt('Unselect').'</a>'.('&nbsp;'x2).
  297:             '</td></tr>'.$/;
  298:         $Str.= $seq->{'html'};
  299:     }
  300:     $Str .= '</table>'.$/;
  301:     return $Str;
  302: }
  303: 
  304: sub new_accumulator {
  305:     my ($title,$src,$symb,$seq_id,$inputname) = @_;
  306:     my $target;
  307:     my $item_id=0;
  308:     return 
  309:         sub {
  310:             if (@_) { 
  311:                 my ($res,$checked) = @_;
  312:                 $target.='<tr><td><label>'.
  313:                     '<input type="checkbox" name="'.$inputname.'" ';
  314:                 if ($checked) {
  315:                     $target .= 'checked ';
  316:                 }
  317:                 $target .= 'id="'.$seq_id.':'.$item_id++.'" ';
  318:                 $target.= 
  319:                     'value="'.&Apache::lonnet::escape($res->symb).'" />'.
  320:                     '&nbsp;'.$res->compTitle.'</label>'.
  321:                     ('&nbsp;'x2).'<a target="preview" '.
  322:                     'href="'.$res->src.'?symb='.
  323:                          &Apache::lonnet::escape($res->symb).'">view</a>'.
  324:                     '</td></tr>'.$/;
  325:             } else { 
  326:                 if (defined($target)) {
  327:                     return { title => $title,
  328:                              symb  => $symb,
  329:                              src   => $src,
  330:                              id    => $seq_id,
  331:                              html  => $target, }; 
  332:                 }
  333:                 return undef;
  334:             }
  335:         };
  336: }
  337: 
  338: sub get_selected_symbs {
  339:     my ($inputfield) = @_;
  340:     my $field = 'form.'.$inputfield;
  341:     my @symbs = (map {
  342:                      &Apache::lonnet::unescape($_);
  343:                      } &Apache::loncommon::get_env_multiple($field));
  344:     return @symbs;
  345: }
  346: 
  347: ####################################################
  348: ####################################################
  349: 
  350: =pod
  351: 
  352: =item &make_target_id($target)
  353: 
  354: Inputs: Hash ref with the following entries:
  355:     $target->{'symb'}, $target->{'part'}, $target->{'respid'}, 
  356:     $target->{'resptype'}.
  357: 
  358: Returns: A string, suitable for a form parameter, which uniquely identifies
  359: the problem, part, and response to do statistical analysis on.
  360: 
  361: Used by Apache::lonstathelpers::ProblemSelector().
  362: 
  363: =cut
  364: 
  365: ####################################################
  366: ####################################################
  367: sub make_target_id {
  368:     my ($target) = @_;
  369:     my $id = &Apache::lonnet::escape($target->{'symb'}).':'.
  370:              &Apache::lonnet::escape($target->{'part'}).':'.
  371:              &Apache::lonnet::escape($target->{'respid'}).':'.
  372:              &Apache::lonnet::escape($target->{'resptype'});
  373:     return $id;
  374: }
  375: 
  376: ####################################################
  377: ####################################################
  378: 
  379: =pod
  380: 
  381: =item &get_target_from_id($id)
  382: 
  383: Inputs: $id, a scalar string from Apache::lonstathelpers::make_target_id().
  384: 
  385: Returns: A hash reference, $target, containing the following keys:
  386:     $target->{'symb'}, $target->{'part'}, $target->{'respid'}, 
  387:     $target->{'resptype'}.
  388: 
  389: =cut
  390: 
  391: ####################################################
  392: ####################################################
  393: sub get_target_from_id {
  394:     my ($id) = @_;
  395:     if (! ref($id)) {
  396:         my ($symb,$part,$respid,$resptype) = split(':',$id);
  397:         return ({ symb     => &Apache::lonnet::unescape($symb),
  398:                   part     => &Apache::lonnet::unescape($part),
  399:                   respid   => &Apache::lonnet::unescape($respid),
  400:                   resptype => &Apache::lonnet::unescape($resptype)});
  401:     } elsif (ref($id) eq 'ARRAY') {
  402:         my @Return;
  403:         foreach my $selected (@$id) {
  404:             my ($symb,$part,$respid,$resptype) = split(':',$selected);
  405:             push(@Return,{ symb     => &Apache::lonnet::unescape($symb),
  406:                            part     => &Apache::lonnet::unescape($part),
  407:                            respid   => &Apache::lonnet::unescape($respid),
  408:                            resptype => &Apache::lonnet::unescape($resptype)});
  409:         }
  410:         return \@Return;
  411:     }
  412: }
  413: 
  414: ####################################################
  415: ####################################################
  416: 
  417: =pod
  418: 
  419: =item &get_prev_curr_next($target,$AcceptableResponseTypes,$granularity)
  420: 
  421: Determine the problem parts or responses preceeding and following the
  422: current resource.
  423: 
  424: Inputs: $target (see &Apache::lonstathelpers::get_target_from_id())
  425:   $AcceptableResponseTypes, regular expression matching acceptable
  426:                             response types,
  427:   $granularity, either 'part', 'response', or 'part_survey'
  428: 
  429: Returns: three hash references, $prev, $curr, $next, which refer to the
  430: preceeding, current, or following problem parts or responses, depending
  431: on the value of $granularity.  Values of undef indicate there is no
  432: previous or next part/response.  A value of undef for all three indicates
  433: there was no match found to the current part/resource.
  434: 
  435: The hash references contain the following keys:
  436:     symb, part, resource
  437: 
  438: If $granularity eq 'response', the following ADDITIONAL keys will be present:
  439:     respid, resptype
  440: 
  441: =cut
  442: 
  443: ####################################################
  444: ####################################################
  445: sub get_prev_curr_next {
  446:     my ($target,$AcceptableResponseTypes,$granularity) = @_;
  447:     #
  448:     # Build an array with the data we need to search through
  449:     my @Resource;
  450:     my ($navmap,@sequences) = 
  451:         &Apache::lonstatistics::selected_sequences_with_assessments('all');
  452:     return $navmap if (! ref($navmap));
  453:     foreach my $seq (@sequences) {
  454:         my @resources = &get_resources($navmap,$seq);
  455:         foreach my $res (@resources) {
  456:             foreach my $part (@{$res->parts}) {
  457:                 if ($res->is_survey($part) && ($granularity eq 'part_survey')){
  458:                     push (@Resource,
  459:                           { symb     => $res->symb,
  460:                             part     => $part,
  461:                             resource => $res,
  462:                         } );
  463:                 } elsif ($granularity eq 'part') {
  464:                     push (@Resource,
  465:                           { symb     => $res->symb,
  466:                             part     => $part,
  467:                             resource => $res,
  468:                         } );
  469:                 } elsif ($granularity eq 'response') {
  470:                     my @response_ids   = $res->responseIds($part);
  471:                     my @response_types = $res->responseType($part);
  472:                     for (my $i=0;
  473:                          $i<scalar(@response_ids);
  474:                          $i++){
  475:                         my $respid   = $response_ids[$i];
  476:                         my $resptype = $response_types[$i];
  477:                         next if ($resptype !~ m/$AcceptableResponseTypes/);
  478:                         push (@Resource,
  479:                               { symb     => $res->symb,
  480:                                 part     => $part,
  481:                                 respid   => $respid,
  482:                                 resptype => $resptype,
  483:                                 resource => $res,
  484:                                 } );
  485:                     }
  486:                 }
  487:             }
  488:         }
  489:     }
  490:     #
  491:     # Get the index of the current situation
  492:     my $curr_idx;
  493:     for ($curr_idx=0;$curr_idx<$#Resource;$curr_idx++) {
  494:         my $curr_item = $Resource[$curr_idx];
  495:         if ($granularity eq 'part' || $granularity eq 'part_survey') {
  496:             if ($curr_item->{'symb'} eq $target->{'symb'} &&
  497:                 $curr_item->{'part'} eq $target->{'part'}) {
  498:                 last;
  499:             }
  500:         } elsif ($granularity eq 'response') {
  501:             if ($curr_item->{'symb'} eq $target->{'symb'} &&
  502:                 $curr_item->{'part'} eq $target->{'part'} &&
  503:                 $curr_item->{'respid'} eq $target->{'respid'} &&
  504:                 $curr_item->{'resptype'} eq $target->{'resptype'}) {
  505:                 last;
  506:             }
  507:         }
  508:     }
  509:     my $curr_item = $Resource[$curr_idx];
  510:     if ($granularity eq 'part' || $granularity eq 'part_survey') {
  511:         if ($curr_item->{'symb'}     ne $target->{'symb'} ||
  512:             $curr_item->{'part'}     ne $target->{'part'}) {
  513:             # bogus symb - return nothing
  514:             return (undef,undef,undef);
  515:         }
  516:     } elsif ($granularity eq 'response') {
  517:         if ($curr_item->{'symb'}     ne $target->{'symb'} ||
  518:             $curr_item->{'part'}     ne $target->{'part'} ||
  519:             $curr_item->{'respid'}   ne $target->{'respid'} ||
  520:             $curr_item->{'resptype'} ne $target->{'resptype'}){
  521:             # bogus symb - return nothing
  522:             return (undef,undef,undef);
  523:         }
  524:     }
  525:     #
  526:     # Now just pick up the data we need
  527:     my ($prev,$curr,$next);
  528:     if ($curr_idx == 0) {
  529:         $prev = undef;
  530:         $curr = $Resource[$curr_idx  ];
  531:         $next = $Resource[$curr_idx+1];
  532:     } elsif ($curr_idx == $#Resource) {
  533:         $prev = $Resource[$curr_idx-1];
  534:         $curr = $Resource[$curr_idx  ];
  535:         $next = undef;
  536:     } else {
  537:         $prev = $Resource[$curr_idx-1];
  538:         $curr = $Resource[$curr_idx  ];
  539:         $next = $Resource[$curr_idx+1];
  540:     }
  541:     return ($navmap,$prev,$curr,$next);
  542: }
  543: 
  544: 
  545: #####################################################
  546: #####################################################
  547: 
  548: =pod
  549: 
  550: =item GetStudentAnswers($r,$problem,$Students)
  551: 
  552: Determines the correct answer for a set of students on a given problem.
  553: The students answers are stored in the student hashes pointed to by the
  554: array @$Students under the key 'answer'.
  555: 
  556: Inputs: $r
  557: $problem: hash reference containing the keys 'resource', 'part', and 'respid'.
  558: $Students: reference to array containing student hashes (need 'username', 
  559:     'domain').  
  560: 
  561: Returns: nothing 
  562: 
  563: =cut
  564: 
  565: #####################################################
  566: #####################################################
  567: sub GetStudentAnswers {
  568:     my ($r,$problem,$Students,$formname,$inputname) = @_;
  569:     my %answers;
  570:     my $status_type;
  571:     if (defined($formname)) {
  572:         $status_type = 'inline';
  573:     } else {
  574:         $status_type = 'popup';
  575:     }    
  576:     my $c = $r->connection();
  577:     my %Answers;
  578:     my ($resource,$partid,$respid) = ($problem->{'resource'},
  579:                                       $problem->{'part'},
  580:                                       $problem->{'respid'});
  581:     # Read in the cache (if it exists) before we start timing things.
  582:     &Apache::lonstathelpers::ensure_proper_cache($resource->{'symb'});
  583:     # Open progress window
  584:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
  585:         ($r,'Student Answer Compilation Status',
  586:          'Student Answer Compilation Progress', scalar(@$Students),
  587:          $status_type,undef,$formname,$inputname);
  588:     $r->rflush();
  589:     foreach my $student (@$Students) {
  590:         last if ($c->aborted());
  591:         my $sname = $student->{'username'};
  592:         my $sdom = $student->{'domain'};
  593:         my $answer = &Apache::lonstathelpers::get_student_answer
  594:             ($resource,$sname,$sdom,$partid,$respid);
  595:         &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
  596:                                                  &mt('last student'));
  597:         $answers{$answer}++;
  598:         $student->{'answer'} = $answer;
  599:     }
  600:     &Apache::lonstathelpers::write_analysis_cache();
  601:     return if ($c->aborted());
  602:     $r->rflush();
  603:     # close progress window
  604:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
  605:     return \%answers;
  606: }
  607: 
  608: #####################################################
  609: #####################################################
  610: 
  611: =pod
  612: 
  613: =item analyze_problem_as_student
  614: 
  615: Analyzes a homework problem for a student
  616: 
  617: Inputs: $resource: a resource object
  618:         $sname, $sdom, $partid, $respid
  619: 
  620: Returns: the problem analysis hash
  621: 
  622: =cut
  623: 
  624: #####################################################
  625: #####################################################
  626: sub analyze_problem_as_student {
  627:     my ($resource,$sname,$sdom) = @_;
  628:     if (ref($resource) ne 'HASH') {
  629:         my $res = $resource;
  630:         $resource = { 'src' => $res->src,
  631:                       'symb' => $res->symb,
  632:                       'parts' => $res->parts };
  633:         foreach my $part (@{$resource->{'parts'}}) {
  634:             $resource->{'partdata'}->{$part}->{'ResponseIds'}=
  635:                 [$res->responseIds($part)];
  636:         }
  637:     }
  638:     my $url = $resource->{'src'};
  639:     my $symb = $resource->{'symb'};
  640:     my $analysis = &get_from_analysis_cache($sname,$sdom,$symb);
  641:     if (! defined($analysis)) {
  642:         my $courseid = $env{'request.course.id'};
  643:         my $Answ=&Apache::lonnet::ssi($url,('grade_target' => 'analyze',
  644:                                             'grade_domain' => $sdom,
  645:                                             'grade_username' => $sname,
  646:                                             'grade_symb' => $symb,
  647:                                             'grade_courseid' => $courseid));
  648:         (my $garbage,$analysis)=split(/_HASH_REF__/,$Answ,2);
  649:         &store_analysis($sname,$sdom,$symb,$analysis);
  650:     }
  651:     my %Answer=&Apache::lonnet::str2hash($analysis);
  652:     #
  653:     return \%Answer;
  654: }
  655: 
  656: #####################################################
  657: #####################################################
  658: 
  659: =pod
  660: 
  661: =item get_student_answer
  662: 
  663: Analyzes a homework problem for a particular student and returns the correct 
  664: answer.  Attempts to put together an answer for problem types 
  665: that do not natively support it.
  666: 
  667: Inputs: $resource: a resource object (from navmaps or hash from loncoursedata)
  668:         $sname, $sdom, $partid, $respid
  669: 
  670: Returns: $answer
  671: 
  672: If $partid and $respid are specified, $answer is simply a scalar containing
  673: the correct answer for the response.
  674: 
  675: If $partid or $respid are undefined, $answer will be a hash reference with
  676: keys $partid.'.'.$respid.'.answer'.
  677: 
  678: =cut
  679: 
  680: #####################################################
  681: #####################################################
  682: sub get_student_answer {
  683:     my ($resource,$sname,$sdom,$partid,$respid) = @_;
  684:     #
  685:     if (ref($resource) ne 'HASH') {
  686:         my $res = $resource;
  687:         $resource = { 'src' => $res->src,
  688:                       'symb' => $res->symb,
  689:                       'parts' => $res->parts };
  690:         foreach my $part (@{$resource->{'parts'}}) {
  691:             $resource->{'partdata'}->{$part}->{'ResponseIds'}=
  692:                 [$res->responseIds($part)];
  693:         }
  694:     }
  695:     #
  696:     my $analysis = 
  697:         &analyze_problem_as_student($resource,$sname,$sdom);
  698:     my $answer;
  699:     foreach my $partid (@{$resource->{'parts'}}) {
  700:         my $partdata = $resource->{'partdata'}->{$partid};
  701:         foreach my $respid (@{$partdata->{'ResponseIds'}}) {
  702:             my $prefix = $partid.'.'.$respid;
  703:             my $key = $prefix.'.answer';
  704:             $answer->{$partid}->{$respid} = 
  705:                 &get_answer($prefix,$key,%$analysis);
  706:         }
  707:     }
  708:     my $returnvalue;
  709:     if (! defined($partid)) {
  710:         $returnvalue = $answer;
  711:     } elsif (! defined($respid)) {
  712:         $returnvalue = $answer->{$partid};
  713:     } else {
  714:         $returnvalue = $answer->{$partid}->{$respid};
  715:     }
  716:     return $returnvalue;
  717: }
  718: 
  719: sub get_answer {
  720:     my ($prefix,$key,%Answer) = @_;
  721:     my $returnvalue;
  722:     if (exists($Answer{$key})) {
  723:         my $student_answer = $Answer{$key}->[0];
  724:         if (! defined($student_answer)) {
  725:             $student_answer = $Answer{$key}->[1];
  726:         }
  727:         $returnvalue = $student_answer;
  728:     } else {
  729:         if (exists($Answer{$prefix.'.shown'})) {
  730:             # The response has foils
  731:             my %values;
  732:             while (my ($k,$v) = each(%Answer)) {
  733:                 next if ($k !~ /^$prefix\.foil\.(value|area)\.(.*)$/);
  734:                 my $foilname = $2;
  735:                 $values{$foilname}=$v;
  736:             }
  737:             foreach my $foil (@{$Answer{$prefix.'.shown'}}) {
  738:                 if (ref($values{$foil}) eq 'ARRAY') {
  739:                     $returnvalue.=&HTML::Entities::encode($foil,'<>&"').'='.
  740:                         join(',',map {&HTML::Entities::encode($_,'<>&"')} @{$values{$foil}}).'&';
  741:                 } else {
  742:                     $returnvalue.=&HTML::Entities::encode($foil,'<>&"').'='.
  743:                         &HTML::Entities::encode($values{$foil},'<>&"').'&';
  744:                 }
  745:             }
  746:             $returnvalue =~ s/ /\%20/g;
  747:             chop ($returnvalue);
  748:         }
  749:     }
  750:     return $returnvalue;
  751: }
  752: 
  753: #####################################################
  754: #####################################################
  755: 
  756: =pod
  757: 
  758: =item Caching routines
  759: 
  760: =over 4
  761: 
  762: =item &load_analysis_cache($symb)
  763: 
  764: Loads the cache for the given symb into memory from disk.  
  765: Requires the cache filename be set.  
  766: Only should be called by &ensure_proper_cache.
  767: 
  768: =cut
  769: 
  770: #####################################################
  771: #####################################################
  772: {
  773:     my $cache_filename = undef;
  774:     my $current_symb = undef;
  775:     my %cache;
  776: 
  777: sub load_analysis_cache {
  778:     my ($symb) = @_;
  779:     return if (! defined($cache_filename));
  780:     if (! defined($current_symb) || $current_symb ne $symb) {
  781:         undef(%cache);
  782:         my $storedstring;
  783:         my %cache_db;
  784:         if (tie(%cache_db,'GDBM_File',$cache_filename,&GDBM_READER(),0640)) {
  785:             $storedstring = $cache_db{&Apache::lonnet::escape($symb)};
  786:             untie(%cache_db);
  787:         }
  788:         if (defined($storedstring)) {
  789:             %cache = %{thaw($storedstring)};
  790:         }
  791:     }
  792:     return;
  793: }
  794: 
  795: #####################################################
  796: #####################################################
  797: 
  798: =pod
  799: 
  800: =item &get_from_analysis_cache($sname,$sdom,$symb,$partid,$respid)
  801: 
  802: Returns the appropriate data from the cache, or undef if no data exists.
  803: 
  804: =cut
  805: 
  806: #####################################################
  807: #####################################################
  808: sub get_from_analysis_cache {
  809:     my ($sname,$sdom,$symb) = @_;
  810:     &ensure_proper_cache($symb);
  811:     my $returnvalue;
  812:     if (exists($cache{$sname.':'.$sdom})) {
  813:         $returnvalue = $cache{$sname.':'.$sdom};
  814:     } else {
  815:         $returnvalue = undef;
  816:     }
  817:     return $returnvalue;
  818: }
  819: 
  820: #####################################################
  821: #####################################################
  822: 
  823: =pod
  824: 
  825: =item &write_analysis_cache($symb)
  826: 
  827: Writes the in memory cache to disk so that it can be read in with
  828: &load_analysis_cache($symb).
  829: 
  830: =cut
  831: 
  832: #####################################################
  833: #####################################################
  834: sub write_analysis_cache {
  835:     return if (! defined($current_symb) || ! defined($cache_filename));
  836:     my %cache_db;
  837:     my $key = &Apache::lonnet::escape($current_symb);
  838:     if (tie(%cache_db,'GDBM_File',$cache_filename,&GDBM_WRCREAT(),0640)) {
  839:         my $storestring = freeze(\%cache);
  840:         $cache_db{$key}=$storestring;
  841:         $cache_db{$key.'.time'}=time;
  842:         untie(%cache_db);
  843:     }
  844:     undef(%cache);
  845:     undef($current_symb);
  846:     undef($cache_filename);
  847:     return;
  848: }
  849: 
  850: #####################################################
  851: #####################################################
  852: 
  853: =pod
  854: 
  855: =item &ensure_proper_cache($symb)
  856: 
  857: Called to make sure we have the proper cache set up.  This is called
  858: prior to every analysis lookup.
  859: 
  860: =cut
  861: 
  862: #####################################################
  863: #####################################################
  864: sub ensure_proper_cache {
  865:     my ($symb) = @_;
  866:     my $cid = $env{'request.course.id'};
  867:     my $new_filename =  '/home/httpd/perl/tmp/'.
  868:         'problemanalysis_'.$cid.'_analysis_cache.db';
  869:     if (! defined($cache_filename) ||
  870:         $cache_filename ne $new_filename ||
  871:         ! defined($current_symb)   ||
  872:         $current_symb ne $symb) {
  873:         $cache_filename = $new_filename;
  874:         # Notice: $current_symb is not set to $symb until after the cache is
  875:         # loaded.  This is what tells &load_analysis_cache to load in a new
  876:         # symb cache.
  877:         &load_analysis_cache($symb);
  878:         $current_symb = $symb;
  879:     }
  880: }
  881: 
  882: #####################################################
  883: #####################################################
  884: 
  885: =pod
  886: 
  887: =item &store_analysis($sname,$sdom,$symb,$partid,$respid,$dataset)
  888: 
  889: Stores the analysis data in the in memory cache.
  890: 
  891: =cut
  892: 
  893: #####################################################
  894: #####################################################
  895: sub store_analysis {
  896:     my ($sname,$sdom,$symb,$dataset) = @_;
  897:     return if ($symb ne $current_symb);
  898:     $cache{$sname.':'.$sdom}=$dataset;
  899:     return;
  900: }
  901: 
  902: }
  903: #####################################################
  904: #####################################################
  905: 
  906: =pod
  907: 
  908: =back
  909: 
  910: =cut
  911: 
  912: #####################################################
  913: #####################################################
  914: 
  915: ##
  916: ## The following is copied from datecalc1.pl, part of the 
  917: ## Spreadsheet::WriteExcel CPAN module.
  918: ##
  919: ##
  920: ######################################################################
  921: #
  922: # Demonstration of writing date/time cells to Excel spreadsheets,
  923: # using UNIX/Perl time as source of date/time.
  924: #
  925: # Copyright 2000, Andrew Benham, adsb@bigfoot.com
  926: #
  927: ######################################################################
  928: #
  929: # UNIX/Perl time is the time since the Epoch (00:00:00 GMT, 1 Jan 1970)
  930: # measured in seconds.
  931: #
  932: # An Excel file can use exactly one of two different date/time systems.
  933: # In these systems, a floating point number represents the number of days
  934: # (and fractional parts of the day) since a start point. The floating point
  935: # number is referred to as a 'serial'.
  936: # The two systems ('1900' and '1904') use different starting points:
  937: #  '1900'; '1.00' is 1 Jan 1900 BUT 1900 is erroneously regarded as
  938: #          a leap year - see:
  939: #            http://support.microsoft.com/support/kb/articles/Q181/3/70.asp
  940: #          for the excuse^H^H^H^H^H^Hreason.
  941: #  '1904'; '1.00' is 2 Jan 1904.
  942: #
  943: # The '1904' system is the default for Apple Macs. Windows versions of
  944: # Excel have the option to use the '1904' system.
  945: #
  946: # Note that Visual Basic's "DateSerial" function does NOT erroneously
  947: # regard 1900 as a leap year, and thus its serials do not agree with
  948: # the 1900 serials of Excel for dates before 1 Mar 1900.
  949: #
  950: # Note that StarOffice (at least at version 5.2) does NOT erroneously
  951: # regard 1900 as a leap year, and thus its serials do not agree with
  952: # the 1900 serials of Excel for dates before 1 Mar 1900.
  953: #
  954: ######################################################################
  955: #
  956: # Calculation description
  957: # =======================
  958: #
  959: # 1900 system
  960: # -----------
  961: # Unix time is '0' at 00:00:00 GMT 1 Jan 1970, i.e. 70 years after 1 Jan 1900.
  962: # Of those 70 years, 17 (1904,08,12,16,20,24,28,32,36,40,44,48,52,56,60,64,68)
  963: # were leap years with an extra day.
  964: # Thus there were 17 + 70*365 days = 25567 days between 1 Jan 1900 and
  965: # 1 Jan 1970.
  966: # In the 1900 system, '1' is 1 Jan 1900, but as 1900 was not a leap year
  967: # 1 Jan 1900 should really be '2', so 1 Jan 1970 is '25569'.
  968: #
  969: # 1904 system
  970: # -----------
  971: # Unix time is '0' at 00:00:00 GMT 1 Jan 1970, i.e. 66 years after 1 Jan 1904.
  972: # Of those 66 years, 17 (1904,08,12,16,20,24,28,32,36,40,44,48,52,56,60,64,68)
  973: # were leap years with an extra day.
  974: # Thus there were 17 + 66*365 days = 24107 days between 1 Jan 1904 and
  975: # 1 Jan 1970.
  976: # In the 1904 system, 2 Jan 1904 being '1', 1 Jan 1970 is '24107'.
  977: #
  978: ######################################################################
  979: #
  980: # Copyright (c) 2000, Andrew Benham.
  981: # This program is free software. It may be used, redistributed and/or
  982: # modified under the same terms as Perl itself.
  983: #
  984: # Andrew Benham, adsb@bigfoot.com
  985: # London, United Kingdom
  986: # 11 Nov 2000
  987: #
  988: ######################################################################
  989: #-----------------------------------------------------------
  990: # calc_serial()
  991: #
  992: # Called with (up to) 2 parameters.
  993: #   1.  Unix timestamp.  If omitted, uses current time.
  994: #   2.  GMT flag. Set to '1' to return serial in GMT.
  995: #       If omitted, returns serial in appropriate timezone.
  996: #
  997: # Returns date/time serial according to $DATE_SYSTEM selected
  998: #-----------------------------------------------------------
  999: sub calc_serial {
 1000:     # Use 1900 date system on all platforms other than Apple Mac (for which
 1001:     # use 1904 date system).
 1002:     my $DATE_SYSTEM = ($^O eq 'MacOS') ? 1 : 0;
 1003:     my $time = (defined $_[0]) ? $_[0] : time();
 1004:     my $gmtflag = (defined $_[1]) ? $_[1] : 0;
 1005:     #
 1006:     # Divide timestamp by number of seconds in a day.
 1007:     # This gives a date serial with '0' on 1 Jan 1970.
 1008:     my $serial = $time / 86400;
 1009:     #
 1010:     # Adjust the date serial by the offset appropriate to the
 1011:     # currently selected system (1900/1904).
 1012:     if ($DATE_SYSTEM == 0) {        # use 1900 system
 1013:         $serial += 25569;
 1014:     } else {                        # use 1904 system
 1015:         $serial += 24107;
 1016:     }
 1017:     #
 1018:     unless ($gmtflag) {
 1019:         # Now have a 'raw' serial with the right offset. But this
 1020:         # gives a serial in GMT, which is false unless the timezone
 1021:         # is GMT. We need to adjust the serial by the appropriate
 1022:         # timezone offset.
 1023:         # Calculate the appropriate timezone offset by seeing what
 1024:         # the differences between localtime and gmtime for the given
 1025:         # time are.
 1026:         #    
 1027:         my @gmtime = gmtime($time);
 1028:         my @ltime  = localtime($time);
 1029:         #
 1030:         # For the first 7 elements of the two arrays, adjust the
 1031:         # date serial where the elements differ.
 1032:         for (0 .. 6) {
 1033:             my $diff = $ltime[$_] - $gmtime[$_];
 1034:             if ($diff) {
 1035:                 $serial += _adjustment($diff,$_);
 1036:             }
 1037:         }
 1038:     }
 1039:     #
 1040:     # Perpetuate the error that 1900 was a leap year by decrementing
 1041:     # the serial if we're using the 1900 system and the date is prior to
 1042:     # 1 Mar 1900. This has the effect of making serial value '60'
 1043:     # 29 Feb 1900.
 1044:     #
 1045:     # This fix only has any effect if UNIX/Perl time on the platform
 1046:     # can represent 1900. Many can't.
 1047:     #
 1048:     unless ($DATE_SYSTEM) {
 1049:         $serial-- if ($serial < 61);    # '61' is 1 Mar 1900
 1050:     }
 1051:     return $serial;
 1052: }
 1053: 
 1054: sub _adjustment {
 1055:     # Based on the difference in the localtime/gmtime array elements
 1056:     # number, return the adjustment required to the serial.
 1057:     #
 1058:     # We only look at some elements of the localtime/gmtime arrays:
 1059:     #    seconds    unlikely to be different as all known timezones
 1060:     #               have an offset of integral multiples of 15 minutes,
 1061:     #               but it's easy to do.
 1062:     #    minutes    will be different for timezone offsets which are
 1063:     #               not an exact number of hours.
 1064:     #    hours      very likely to be different.
 1065:     #    weekday    will differ when localtime/gmtime difference
 1066:     #               straddles midnight.
 1067:     #
 1068:     # Assume that difference between localtime and gmtime is less than
 1069:     # 5 days, then don't have to do maths for day of month, month number,
 1070:     # year number, etc...
 1071:     #
 1072:     my ($delta,$element) = @_;
 1073:     my $adjust = 0;
 1074:     #
 1075:     if ($element == 0) {            # Seconds
 1076:         $adjust = $delta/86400;         # 60 * 60 * 24
 1077:     } elsif ($element == 1) {       # Minutes
 1078:         $adjust = $delta/1440;          # 60 * 24
 1079:     } elsif ($element == 2) {       # Hours
 1080:         $adjust = $delta/24;            # 24
 1081:     } elsif ($element == 6) {       # Day of week number
 1082:         # Catch difference straddling Sat/Sun in either direction
 1083:         $delta += 7 if ($delta < -4);
 1084:         $delta -= 7 if ($delta > 4);
 1085:         #    
 1086:         $adjust = $delta;
 1087:     }
 1088:     return $adjust;
 1089: }
 1090: 
 1091: ###########################################################
 1092: ###########################################################
 1093: 
 1094: =pod
 1095: 
 1096: =item get_problem_data
 1097: 
 1098: Returns a data structure describing the problem.
 1099: 
 1100: Inputs: $url
 1101: 
 1102: Returns: %Partdata
 1103: 
 1104: =cut
 1105: 
 1106: ## note: we must force each foil and option to not begin or end with
 1107: ##       spaces as they are stored without such data.
 1108: ##
 1109: ###########################################################
 1110: ###########################################################
 1111: sub get_problem_data {
 1112:     my ($url) = @_;
 1113:     my $Answ=&Apache::lonnet::ssi($url,('grade_target' => 'analyze'));
 1114:     (my $garbage,$Answ)=split(/_HASH_REF__/,$Answ,2);
 1115:     my %Answer;
 1116:     %Answer=&Apache::lonnet::str2hash($Answ);
 1117:     my %Partdata;
 1118:     foreach my $part (@{$Answer{'parts'}}) {
 1119:         while (my($key,$value) = each(%Answer)) {
 1120:             #
 1121:             # Logging code:
 1122:             if (0) {
 1123:                 &Apache::lonnet::logthis($part.' got key "'.$key.'"');
 1124:                 if (ref($value) eq 'ARRAY') {
 1125:                     &Apache::lonnet::logthis('    @'.join(',',@$value));
 1126:                 } else {
 1127:                     &Apache::lonnet::logthis('    '.$value);
 1128:                 }
 1129:             }
 1130:             # End of logging code
 1131:             next if ($key !~ /^$part/);
 1132:             $key =~ s/^$part\.//;
 1133:             if (ref($value) eq 'ARRAY') {
 1134:                 if ($key eq 'options') {
 1135:                     $Partdata{$part}->{'_Options'}=$value;
 1136:                 } elsif ($key eq 'concepts') {
 1137:                     $Partdata{$part}->{'_Concepts'}=$value;
 1138:                 } elsif ($key eq 'items') {
 1139:                     $Partdata{$part}->{'_Items'}=$value;
 1140:                 } elsif ($key =~ /^concept\.(.*)$/) {
 1141:                     my $concept = $1;
 1142:                     foreach my $foil (@$value) {
 1143:                         $Partdata{$part}->{'_Foils'}->{$foil}->{'_Concept'}=
 1144:                                                                       $concept;
 1145:                     }
 1146:                 } elsif ($key =~ /^(unit|incorrect|answer|ans_low|ans_high|str_type)$/) {
 1147:                     $Partdata{$part}->{$key}=$value;
 1148:                 }
 1149:             } else {
 1150:                 if ($key=~ /^foil\.text\.(.*)$/) {
 1151:                     my $foil = $1;
 1152:                     $Partdata{$part}->{'_Foils'}->{$foil}->{'name'}=$foil;
 1153:                     $value =~ s/(\s*$|^\s*)//g;
 1154:                     $Partdata{$part}->{'_Foils'}->{$foil}->{'text'}=$value;
 1155:                 } elsif ($key =~ /^foil\.value\.(.*)$/) {
 1156:                     my $foil = $1;
 1157:                     $Partdata{$part}->{'_Foils'}->{$foil}->{'value'}=$value;
 1158:                 } elsif ($key eq 'answercomputed') {
 1159:                     $Partdata{$part}->{'answercomputed'} = $value;
 1160:                 }
 1161:             }
 1162:         }
 1163:     }
 1164:     # Further debugging code
 1165:     if (0) {
 1166:         &Apache::lonnet::logthis('lonstathelpers::get_problem_data');
 1167:         &log_hash_ref(\%Partdata);
 1168:     }
 1169:     return %Partdata;
 1170: }
 1171: 
 1172: sub log_array_ref {
 1173:     my ($arrayref,$prefix) = @_;
 1174:     return if (ref($arrayref) ne 'ARRAY');
 1175:     if (! defined($prefix)) { $prefix = ''; };
 1176:     foreach my $v (@$arrayref) {
 1177:         if (ref($v) eq 'ARRAY') {
 1178:             &log_array_ref($v,$prefix.'  ');
 1179:         } elsif (ref($v) eq 'HASH') {
 1180:             &log_hash_ref($v,$prefix.'  ');
 1181:         } else {
 1182:             &Apache::lonnet::logthis($prefix.'"'.$v.'"');
 1183:         }
 1184:     }
 1185: }
 1186: 
 1187: sub log_hash_ref {
 1188:     my ($hashref,$prefix) = @_;
 1189:     return if (ref($hashref) ne 'HASH');
 1190:     if (! defined($prefix)) { $prefix = ''; };
 1191:     while (my ($k,$v) = each(%$hashref)) {
 1192:         if (ref($v) eq 'ARRAY') {
 1193:             &Apache::lonnet::logthis($prefix.'"'.$k.'" = array');
 1194:             &log_array_ref($v,$prefix.'  ');
 1195:         } elsif (ref($v) eq 'HASH') {
 1196:             &Apache::lonnet::logthis($prefix.'"'.$k.'" = hash');
 1197:             &log_hash_ref($v,$prefix.'  ');
 1198:         } else {
 1199:             &Apache::lonnet::logthis($prefix.'"'.$k.'" => "'.$v.'"');
 1200:         }
 1201:     }
 1202: }
 1203: ####################################################
 1204: ####################################################
 1205: 
 1206: =pod
 1207: 
 1208: =item &limit_by_time()
 1209: 
 1210: =cut
 1211: 
 1212: ####################################################
 1213: ####################################################
 1214: sub limit_by_time_form {
 1215:     my $Starttime_form = '';
 1216:     my $starttime = &Apache::lonhtmlcommon::get_date_from_form
 1217:         ('limitby_startdate');
 1218:     my $endtime = &Apache::lonhtmlcommon::get_date_from_form
 1219:         ('limitby_enddate');
 1220:     if (! defined($endtime)) {
 1221:         $endtime = time;
 1222:     }
 1223:     if (! defined($starttime)) {
 1224:         $starttime = $endtime - 60*60*24*7;
 1225:     }
 1226:     my $state;
 1227:     if (&limit_by_time()) {
 1228:         $state = '';
 1229:     } else {
 1230:         $state = 'disabled';
 1231:     }
 1232:     my $startdateform = &Apache::lonhtmlcommon::date_setter
 1233:         ('Statistics','limitby_startdate',$starttime,undef,undef,$state);
 1234:     my $enddateform = &Apache::lonhtmlcommon::date_setter
 1235:         ('Statistics','limitby_enddate',$endtime,undef,undef,$state);
 1236:     my $Str;
 1237:     $Str .= '<script language="Javascript" >';
 1238:     $Str .= 'function toggle_limitby_activity(state) {';
 1239:     $Str .= '    if (state) {';
 1240:     $Str .= '        limitby_startdate_enable();';
 1241:     $Str .= '        limitby_enddate_enable();';
 1242:     $Str .= '    } else {';
 1243:     $Str .= '        limitby_startdate_disable();';
 1244:     $Str .= '        limitby_enddate_disable();';
 1245:     $Str .= '    }';    
 1246:     $Str .= '}';
 1247:     $Str .= '</script>';
 1248:     $Str .= '<fieldset>';
 1249:     my $timecheckbox = '<input type="checkbox" name="limit_by_time" ';
 1250:     if (&limit_by_time()) {
 1251:         $timecheckbox .= ' checked ';
 1252:     } 
 1253:     $timecheckbox .= 'OnChange="javascript:toggle_limitby_activity(this.checked);" ';
 1254:     $timecheckbox .= ' />';
 1255:     $Str .= '<legend><label>'.&mt('[_1] Limit by time',$timecheckbox).'</label></legend>';
 1256:     $Str .= &mt('Start Time: [_1]',$startdateform).'<br />';
 1257:     $Str .= &mt('&nbsp;End Time: [_1]',$enddateform).'<br />';
 1258:     $Str .= '</fieldset>';
 1259:     return $Str;
 1260: }
 1261: 
 1262: sub limit_by_time {
 1263:     if (exists($env{'form.limit_by_time'}) &&
 1264:         $env{'form.limit_by_time'} ne '' ) {
 1265:         return 1;
 1266:     } else {
 1267:         return 0;
 1268:     }
 1269: }
 1270: 
 1271: sub get_time_limits {
 1272:     my $starttime = &Apache::lonhtmlcommon::get_date_from_form
 1273:         ('limitby_startdate');
 1274:     my $endtime = &Apache::lonhtmlcommon::get_date_from_form
 1275:         ('limitby_enddate');
 1276:     return ($starttime,$endtime);
 1277: }
 1278: 
 1279: ####################################################
 1280: ####################################################
 1281: 
 1282: =pod
 1283: 
 1284: =item &manage_caches
 1285: 
 1286: Inputs: $r, apache request object
 1287: 
 1288: Returns: An array of scalars containing html for buttons.
 1289: 
 1290: =cut
 1291: 
 1292: ####################################################
 1293: ####################################################
 1294: sub manage_caches {
 1295:     my ($r,$formname,$inputname,$update_message) = @_;
 1296:     &Apache::loncoursedata::clear_internal_caches();
 1297:     my $sectionkey = 
 1298:         join(',',
 1299:              map {
 1300:                      &Apache::lonnet::escape($_);
 1301:                  } sort(&Apache::lonstatistics::get_selected_sections())
 1302:              );
 1303:     my $statuskey = $Apache::lonstatistics::enrollment_status;
 1304:     if (exists($env{'form.ClearCache'}) || 
 1305:         exists($env{'form.updatecaches'}) || 
 1306:         (exists($env{'form.firstrun'}) && $env{'form.firstrun'} ne 'no') ||
 1307:         (exists($env{'form.prevsection'}) &&
 1308:             $env{'form.prevsection'} ne $sectionkey) ||
 1309:         (exists($env{'form.prevenrollstatus'}) &&
 1310:             $env{'form.prevenrollstatus'} ne $statuskey)
 1311:         ) {
 1312:         if (defined($update_message)) {
 1313:             $r->print($update_message);
 1314:         }
 1315:         if (0) {
 1316:             &Apache::lonnet::logthis('Updating mysql student data caches');
 1317:         }
 1318:         &gather_full_student_data($r,$formname,$inputname);
 1319:     }
 1320:     #
 1321:     my @Buttons = 
 1322:         ('<input type="submit" name="ClearCache" '.
 1323:              'value="'.&mt('Clear Caches').'" />',
 1324:          '<input type="submit" name="updatecaches" '.
 1325:              'value="'.&mt('Update Caches').'" />'.
 1326:          &Apache::loncommon::help_open_topic('Statistics_Cache'),
 1327:          '<input type="hidden" name="prevsection" value="'.$sectionkey.'" />',
 1328:          '<input type="hidden" name="prevenrollstatus" value="'.$statuskey.'" />'
 1329:          );
 1330:     #
 1331:     if (! exists($env{'form.firstrun'})) {
 1332:         $r->print('<input type="hidden" name="firstrun" value="yes" />');
 1333:     } else {
 1334:         $r->print('<input type="hidden" name="firstrun" value="no" />');
 1335:     }
 1336:     #
 1337:     return @Buttons;
 1338: }
 1339: 
 1340: sub gather_full_student_data {
 1341:     my ($r,$formname,$inputname) = @_;
 1342:     my $status_type;
 1343:     if (defined($formname)) {
 1344:         $status_type = 'inline';
 1345:     } else {
 1346:         $status_type = 'popup';
 1347:     }
 1348:     my $c = $r->connection();
 1349:     #
 1350:     &Apache::loncoursedata::clear_internal_caches();
 1351:     #
 1352:     my @Students = @Apache::lonstatistics::Students;
 1353:     #
 1354:     # Open the progress window
 1355:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
 1356:         ($r,&mt('Student Data Compilation Status'),
 1357:          &mt('Student Data Compilation Progress'), scalar(@Students),
 1358:          $status_type,undef,$formname,$inputname);
 1359:     #
 1360:     while (my $student = shift @Students) {
 1361:         return if ($c->aborted());
 1362:         my $status = &Apache::loncoursedata::ensure_current_full_data
 1363:             ($student->{'username'},$student->{'domain'},
 1364:              $env{'request.course.id'});
 1365:         &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 1366:                                                  &mt('last student'));
 1367:     }
 1368:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 1369:     $r->rflush();
 1370:     return;
 1371: }
 1372: 
 1373: ####################################################
 1374: ####################################################
 1375: 
 1376: =pod
 1377: 
 1378: =item &submission_report_form
 1379: 
 1380: Input: The originating reportSelected value for the current stats page.
 1381: 
 1382: Output: Scalar containing HTML with needed form elements and a link to 
 1383: the student submission reports page.
 1384: 
 1385: =cut
 1386: 
 1387: ####################################################
 1388: ####################################################
 1389: sub submission_report_form {
 1390:     my ($original_report) = @_;
 1391:     # Note: In the link below we change the reportSelected value.  If
 1392:     # the user hits the 'back' button on the browser after getting their
 1393:     # student submissions report, this value may still be around.  So we
 1394:     # output a script block to set it properly.  If the $original_report
 1395:     # value is unset, you are just asking for trouble.
 1396:     if (! defined($original_report)) {
 1397:         &Apache::lonnet::logthis
 1398:             ('someone called lonstathelpers::submission_report_form without '.
 1399:              ' enough input.');
 1400:     }
 1401:     my $html = $/.
 1402:         '<script type="Text/JavaScript">'.
 1403:         "document.Statistics.reportSelected.value='$original_report';".
 1404:         '</script>'.
 1405:         '<input type="hidden" name="correctans" value="true" />'.
 1406:         '<input type="hidden" name="prob_status" value="true" />'.
 1407:         '<input type="hidden" name="all_sub" value="true" />';
 1408:     my $output_selector = $/.'<select name="output">'.$/;
 1409:     foreach ('HTML','Excel','CSV') {
 1410:         $output_selector .= '    <option value="'.lc($_).'"';
 1411:         if ($env{'form.output'} eq lc($_)) {
 1412:             $output_selector .= ' selected ';
 1413:         }
 1414:         $output_selector .='>'.&mt($_).'</option>'.$/;
 1415:     } 
 1416:     $output_selector .= '</select>'.$/;
 1417:     my $link = '<a href="javascript:'.
 1418:        q{document.Statistics.reportSelected.value='student_submission_reports';}.
 1419:        'document.Statistics.submit();">';
 1420:     $html.= &mt('View data as [_1] [_2]go[_3]',$output_selector,
 1421:                 $link,'</a>').$/;
 1422:     return $html
 1423: }
 1424: 
 1425: ####################################################
 1426: ####################################################
 1427: 
 1428: =pod
 1429: 
 1430: =back
 1431: 
 1432: =cut
 1433: 
 1434: ####################################################
 1435: ####################################################
 1436: 
 1437: 1;
 1438: 
 1439: __END__

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>