File:  [LON-CAPA] / loncom / interface / statistics / lonstathelpers.pm
Revision 1.47: download - view: text, annotated - select for diffs
Thu Apr 7 07:34:52 2005 UTC (19 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- increasing the use of loncommon::get_env_multiple

    1: # The LearningOnline Network with CAPA
    2: #
    3: # $Id: lonstathelpers.pm,v 1.47 2005/04/07 07:34:52 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 = &Apache::loncommon::get_env_multiple($field);
  342:     @Symbs = (map {&Apache::lonnet::unescape($_);} @{$env{$field}});
  343:     return @Symbs;
  344: }
  345: 
  346: ####################################################
  347: ####################################################
  348: 
  349: =pod
  350: 
  351: =item &make_target_id($target)
  352: 
  353: Inputs: Hash ref with the following entries:
  354:     $target->{'symb'}, $target->{'part'}, $target->{'respid'}, 
  355:     $target->{'resptype'}.
  356: 
  357: Returns: A string, suitable for a form parameter, which uniquely identifies
  358: the problem, part, and response to do statistical analysis on.
  359: 
  360: Used by Apache::lonstathelpers::ProblemSelector().
  361: 
  362: =cut
  363: 
  364: ####################################################
  365: ####################################################
  366: sub make_target_id {
  367:     my ($target) = @_;
  368:     my $id = &Apache::lonnet::escape($target->{'symb'}).':'.
  369:              &Apache::lonnet::escape($target->{'part'}).':'.
  370:              &Apache::lonnet::escape($target->{'respid'}).':'.
  371:              &Apache::lonnet::escape($target->{'resptype'});
  372:     return $id;
  373: }
  374: 
  375: ####################################################
  376: ####################################################
  377: 
  378: =pod
  379: 
  380: =item &get_target_from_id($id)
  381: 
  382: Inputs: $id, a scalar string from Apache::lonstathelpers::make_target_id().
  383: 
  384: Returns: A hash reference, $target, containing the following keys:
  385:     $target->{'symb'}, $target->{'part'}, $target->{'respid'}, 
  386:     $target->{'resptype'}.
  387: 
  388: =cut
  389: 
  390: ####################################################
  391: ####################################################
  392: sub get_target_from_id {
  393:     my ($id) = @_;
  394:     if (! ref($id)) {
  395:         my ($symb,$part,$respid,$resptype) = split(':',$id);
  396:         return ({ symb     => &Apache::lonnet::unescape($symb),
  397:                   part     => &Apache::lonnet::unescape($part),
  398:                   respid   => &Apache::lonnet::unescape($respid),
  399:                   resptype => &Apache::lonnet::unescape($resptype)});
  400:     } elsif (ref($id) eq 'ARRAY') {
  401:         my @Return;
  402:         foreach my $selected (@$id) {
  403:             my ($symb,$part,$respid,$resptype) = split(':',$selected);
  404:             push(@Return,{ symb     => &Apache::lonnet::unescape($symb),
  405:                            part     => &Apache::lonnet::unescape($part),
  406:                            respid   => &Apache::lonnet::unescape($respid),
  407:                            resptype => &Apache::lonnet::unescape($resptype)});
  408:         }
  409:         return \@Return;
  410:     }
  411: }
  412: 
  413: ####################################################
  414: ####################################################
  415: 
  416: =pod
  417: 
  418: =item &get_prev_curr_next($target,$AcceptableResponseTypes,$granularity)
  419: 
  420: Determine the problem parts or responses preceeding and following the
  421: current resource.
  422: 
  423: Inputs: $target (see &Apache::lonstathelpers::get_target_from_id())
  424:   $AcceptableResponseTypes, regular expression matching acceptable
  425:                             response types,
  426:   $granularity, either 'part', 'response', or 'part_survey'
  427: 
  428: Returns: three hash references, $prev, $curr, $next, which refer to the
  429: preceeding, current, or following problem parts or responses, depending
  430: on the value of $granularity.  Values of undef indicate there is no
  431: previous or next part/response.  A value of undef for all three indicates
  432: there was no match found to the current part/resource.
  433: 
  434: The hash references contain the following keys:
  435:     symb, part, resource
  436: 
  437: If $granularity eq 'response', the following ADDITIONAL keys will be present:
  438:     respid, resptype
  439: 
  440: =cut
  441: 
  442: ####################################################
  443: ####################################################
  444: sub get_prev_curr_next {
  445:     my ($target,$AcceptableResponseTypes,$granularity) = @_;
  446:     #
  447:     # Build an array with the data we need to search through
  448:     my @Resource;
  449:     my ($navmap,@sequences) = 
  450:         &Apache::lonstatistics::selected_sequences_with_assessments('all');
  451:     return $navmap if (! ref($navmap));
  452:     foreach my $seq (@sequences) {
  453:         my @resources = &get_resources($navmap,$seq);
  454:         foreach my $res (@resources) {
  455:             foreach my $part (@{$res->parts}) {
  456:                 if ($res->is_survey($part) && ($granularity eq 'part_survey')){
  457:                     push (@Resource,
  458:                           { symb     => $res->symb,
  459:                             part     => $part,
  460:                             resource => $res,
  461:                         } );
  462:                 } elsif ($granularity eq 'part') {
  463:                     push (@Resource,
  464:                           { symb     => $res->symb,
  465:                             part     => $part,
  466:                             resource => $res,
  467:                         } );
  468:                 } elsif ($granularity eq 'response') {
  469:                     my @response_ids   = $res->responseIds($part);
  470:                     my @response_types = $res->responseType($part);
  471:                     for (my $i=0;
  472:                          $i<scalar(@response_ids);
  473:                          $i++){
  474:                         my $respid   = $response_ids[$i];
  475:                         my $resptype = $response_types[$i];
  476:                         next if ($resptype !~ m/$AcceptableResponseTypes/);
  477:                         push (@Resource,
  478:                               { symb     => $res->symb,
  479:                                 part     => $part,
  480:                                 respid   => $respid,
  481:                                 resptype => $resptype,
  482:                                 resource => $res,
  483:                                 } );
  484:                     }
  485:                 }
  486:             }
  487:         }
  488:     }
  489:     #
  490:     # Get the index of the current situation
  491:     my $curr_idx;
  492:     for ($curr_idx=0;$curr_idx<$#Resource;$curr_idx++) {
  493:         my $curr_item = $Resource[$curr_idx];
  494:         if ($granularity eq 'part' || $granularity eq 'part_survey') {
  495:             if ($curr_item->{'symb'} eq $target->{'symb'} &&
  496:                 $curr_item->{'part'} eq $target->{'part'}) {
  497:                 last;
  498:             }
  499:         } elsif ($granularity eq 'response') {
  500:             if ($curr_item->{'symb'} eq $target->{'symb'} &&
  501:                 $curr_item->{'part'} eq $target->{'part'} &&
  502:                 $curr_item->{'respid'} eq $target->{'respid'} &&
  503:                 $curr_item->{'resptype'} eq $target->{'resptype'}) {
  504:                 last;
  505:             }
  506:         }
  507:     }
  508:     my $curr_item = $Resource[$curr_idx];
  509:     if ($granularity eq 'part' || $granularity eq 'part_survey') {
  510:         if ($curr_item->{'symb'}     ne $target->{'symb'} ||
  511:             $curr_item->{'part'}     ne $target->{'part'}) {
  512:             # bogus symb - return nothing
  513:             return (undef,undef,undef);
  514:         }
  515:     } elsif ($granularity eq 'response') {
  516:         if ($curr_item->{'symb'}     ne $target->{'symb'} ||
  517:             $curr_item->{'part'}     ne $target->{'part'} ||
  518:             $curr_item->{'respid'}   ne $target->{'respid'} ||
  519:             $curr_item->{'resptype'} ne $target->{'resptype'}){
  520:             # bogus symb - return nothing
  521:             return (undef,undef,undef);
  522:         }
  523:     }
  524:     #
  525:     # Now just pick up the data we need
  526:     my ($prev,$curr,$next);
  527:     if ($curr_idx == 0) {
  528:         $prev = undef;
  529:         $curr = $Resource[$curr_idx  ];
  530:         $next = $Resource[$curr_idx+1];
  531:     } elsif ($curr_idx == $#Resource) {
  532:         $prev = $Resource[$curr_idx-1];
  533:         $curr = $Resource[$curr_idx  ];
  534:         $next = undef;
  535:     } else {
  536:         $prev = $Resource[$curr_idx-1];
  537:         $curr = $Resource[$curr_idx  ];
  538:         $next = $Resource[$curr_idx+1];
  539:     }
  540:     return ($navmap,$prev,$curr,$next);
  541: }
  542: 
  543: 
  544: #####################################################
  545: #####################################################
  546: 
  547: =pod
  548: 
  549: =item GetStudentAnswers($r,$problem,$Students)
  550: 
  551: Determines the correct answer for a set of students on a given problem.
  552: The students answers are stored in the student hashes pointed to by the
  553: array @$Students under the key 'answer'.
  554: 
  555: Inputs: $r
  556: $problem: hash reference containing the keys 'resource', 'part', and 'respid'.
  557: $Students: reference to array containing student hashes (need 'username', 
  558:     'domain').  
  559: 
  560: Returns: nothing 
  561: 
  562: =cut
  563: 
  564: #####################################################
  565: #####################################################
  566: sub GetStudentAnswers {
  567:     my ($r,$problem,$Students,$formname,$inputname) = @_;
  568:     my %answers;
  569:     my $status_type;
  570:     if (defined($formname)) {
  571:         $status_type = 'inline';
  572:     } else {
  573:         $status_type = 'popup';
  574:     }    
  575:     my $c = $r->connection();
  576:     my %Answers;
  577:     my ($resource,$partid,$respid) = ($problem->{'resource'},
  578:                                       $problem->{'part'},
  579:                                       $problem->{'respid'});
  580:     # Read in the cache (if it exists) before we start timing things.
  581:     &Apache::lonstathelpers::ensure_proper_cache($resource->{'symb'});
  582:     # Open progress window
  583:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
  584:         ($r,'Student Answer Compilation Status',
  585:          'Student Answer Compilation Progress', scalar(@$Students),
  586:          $status_type,undef,$formname,$inputname);
  587:     $r->rflush();
  588:     foreach my $student (@$Students) {
  589:         last if ($c->aborted());
  590:         my $sname = $student->{'username'};
  591:         my $sdom = $student->{'domain'};
  592:         my $answer = &Apache::lonstathelpers::get_student_answer
  593:             ($resource,$sname,$sdom,$partid,$respid);
  594:         &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
  595:                                                  &mt('last student'));
  596:         $answers{$answer}++;
  597:         $student->{'answer'} = $answer;
  598:     }
  599:     &Apache::lonstathelpers::write_analysis_cache();
  600:     return if ($c->aborted());
  601:     $r->rflush();
  602:     # close progress window
  603:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
  604:     return \%answers;
  605: }
  606: 
  607: #####################################################
  608: #####################################################
  609: 
  610: =pod
  611: 
  612: =item analyze_problem_as_student
  613: 
  614: Analyzes a homework problem for a student
  615: 
  616: Inputs: $resource: a resource object
  617:         $sname, $sdom, $partid, $respid
  618: 
  619: Returns: the problem analysis hash
  620: 
  621: =cut
  622: 
  623: #####################################################
  624: #####################################################
  625: sub analyze_problem_as_student {
  626:     my ($resource,$sname,$sdom) = @_;
  627:     if (ref($resource) ne 'HASH') {
  628:         my $res = $resource;
  629:         $resource = { 'src' => $res->src,
  630:                       'symb' => $res->symb,
  631:                       'parts' => $res->parts };
  632:         foreach my $part (@{$resource->{'parts'}}) {
  633:             $resource->{'partdata'}->{$part}->{'ResponseIds'}=
  634:                 [$res->responseIds($part)];
  635:         }
  636:     }
  637:     my $url = $resource->{'src'};
  638:     my $symb = $resource->{'symb'};
  639:     my $analysis = &get_from_analysis_cache($sname,$sdom,$symb);
  640:     if (! defined($analysis)) {
  641:         my $courseid = $env{'request.course.id'};
  642:         my $Answ=&Apache::lonnet::ssi($url,('grade_target' => 'analyze',
  643:                                             'grade_domain' => $sdom,
  644:                                             'grade_username' => $sname,
  645:                                             'grade_symb' => $symb,
  646:                                             'grade_courseid' => $courseid));
  647:         (my $garbage,$analysis)=split(/_HASH_REF__/,$Answ,2);
  648:         &store_analysis($sname,$sdom,$symb,$analysis);
  649:     }
  650:     my %Answer=&Apache::lonnet::str2hash($analysis);
  651:     #
  652:     return \%Answer;
  653: }
  654: 
  655: #####################################################
  656: #####################################################
  657: 
  658: =pod
  659: 
  660: =item get_student_answer
  661: 
  662: Analyzes a homework problem for a particular student and returns the correct 
  663: answer.  Attempts to put together an answer for problem types 
  664: that do not natively support it.
  665: 
  666: Inputs: $resource: a resource object (from navmaps or hash from loncoursedata)
  667:         $sname, $sdom, $partid, $respid
  668: 
  669: Returns: $answer
  670: 
  671: If $partid and $respid are specified, $answer is simply a scalar containing
  672: the correct answer for the response.
  673: 
  674: If $partid or $respid are undefined, $answer will be a hash reference with
  675: keys $partid.'.'.$respid.'.answer'.
  676: 
  677: =cut
  678: 
  679: #####################################################
  680: #####################################################
  681: sub get_student_answer {
  682:     my ($resource,$sname,$sdom,$partid,$respid) = @_;
  683:     #
  684:     if (ref($resource) ne 'HASH') {
  685:         my $res = $resource;
  686:         $resource = { 'src' => $res->src,
  687:                       'symb' => $res->symb,
  688:                       'parts' => $res->parts };
  689:         foreach my $part (@{$resource->{'parts'}}) {
  690:             $resource->{'partdata'}->{$part}->{'ResponseIds'}=
  691:                 [$res->responseIds($part)];
  692:         }
  693:     }
  694:     #
  695:     my $analysis = 
  696:         &analyze_problem_as_student($resource,$sname,$sdom);
  697:     my $answer;
  698:     foreach my $partid (@{$resource->{'parts'}}) {
  699:         my $partdata = $resource->{'partdata'}->{$partid};
  700:         foreach my $respid (@{$partdata->{'ResponseIds'}}) {
  701:             my $prefix = $partid.'.'.$respid;
  702:             my $key = $prefix.'.answer';
  703:             $answer->{$partid}->{$respid} = 
  704:                 &get_answer($prefix,$key,%$analysis);
  705:         }
  706:     }
  707:     my $returnvalue;
  708:     if (! defined($partid)) {
  709:         $returnvalue = $answer;
  710:     } elsif (! defined($respid)) {
  711:         $returnvalue = $answer->{$partid};
  712:     } else {
  713:         $returnvalue = $answer->{$partid}->{$respid};
  714:     }
  715:     return $returnvalue;
  716: }
  717: 
  718: sub get_answer {
  719:     my ($prefix,$key,%Answer) = @_;
  720:     my $returnvalue;
  721:     if (exists($Answer{$key})) {
  722:         my $student_answer = $Answer{$key}->[0];
  723:         if (! defined($student_answer)) {
  724:             $student_answer = $Answer{$key}->[1];
  725:         }
  726:         $returnvalue = $student_answer;
  727:     } else {
  728:         if (exists($Answer{$prefix.'.shown'})) {
  729:             # The response has foils
  730:             my %values;
  731:             while (my ($k,$v) = each(%Answer)) {
  732:                 next if ($k !~ /^$prefix\.foil\.(value|area)\.(.*)$/);
  733:                 my $foilname = $2;
  734:                 $values{$foilname}=$v;
  735:             }
  736:             foreach my $foil (@{$Answer{$prefix.'.shown'}}) {
  737:                 if (ref($values{$foil}) eq 'ARRAY') {
  738:                     $returnvalue.=&HTML::Entities::encode($foil,'<>&"').'='.
  739:                         join(',',map {&HTML::Entities::encode($_,'<>&"')} @{$values{$foil}}).'&';
  740:                 } else {
  741:                     $returnvalue.=&HTML::Entities::encode($foil,'<>&"').'='.
  742:                         &HTML::Entities::encode($values{$foil},'<>&"').'&';
  743:                 }
  744:             }
  745:             $returnvalue =~ s/ /\%20/g;
  746:             chop ($returnvalue);
  747:         }
  748:     }
  749:     return $returnvalue;
  750: }
  751: 
  752: #####################################################
  753: #####################################################
  754: 
  755: =pod
  756: 
  757: =item Caching routines
  758: 
  759: =over 4
  760: 
  761: =item &load_analysis_cache($symb)
  762: 
  763: Loads the cache for the given symb into memory from disk.  
  764: Requires the cache filename be set.  
  765: Only should be called by &ensure_proper_cache.
  766: 
  767: =cut
  768: 
  769: #####################################################
  770: #####################################################
  771: {
  772:     my $cache_filename = undef;
  773:     my $current_symb = undef;
  774:     my %cache;
  775: 
  776: sub load_analysis_cache {
  777:     my ($symb) = @_;
  778:     return if (! defined($cache_filename));
  779:     if (! defined($current_symb) || $current_symb ne $symb) {
  780:         undef(%cache);
  781:         my $storedstring;
  782:         my %cache_db;
  783:         if (tie(%cache_db,'GDBM_File',$cache_filename,&GDBM_READER(),0640)) {
  784:             $storedstring = $cache_db{&Apache::lonnet::escape($symb)};
  785:             untie(%cache_db);
  786:         }
  787:         if (defined($storedstring)) {
  788:             %cache = %{thaw($storedstring)};
  789:         }
  790:     }
  791:     return;
  792: }
  793: 
  794: #####################################################
  795: #####################################################
  796: 
  797: =pod
  798: 
  799: =item &get_from_analysis_cache($sname,$sdom,$symb,$partid,$respid)
  800: 
  801: Returns the appropriate data from the cache, or undef if no data exists.
  802: 
  803: =cut
  804: 
  805: #####################################################
  806: #####################################################
  807: sub get_from_analysis_cache {
  808:     my ($sname,$sdom,$symb) = @_;
  809:     &ensure_proper_cache($symb);
  810:     my $returnvalue;
  811:     if (exists($cache{$sname.':'.$sdom})) {
  812:         $returnvalue = $cache{$sname.':'.$sdom};
  813:     } else {
  814:         $returnvalue = undef;
  815:     }
  816:     return $returnvalue;
  817: }
  818: 
  819: #####################################################
  820: #####################################################
  821: 
  822: =pod
  823: 
  824: =item &write_analysis_cache($symb)
  825: 
  826: Writes the in memory cache to disk so that it can be read in with
  827: &load_analysis_cache($symb).
  828: 
  829: =cut
  830: 
  831: #####################################################
  832: #####################################################
  833: sub write_analysis_cache {
  834:     return if (! defined($current_symb) || ! defined($cache_filename));
  835:     my %cache_db;
  836:     my $key = &Apache::lonnet::escape($current_symb);
  837:     if (tie(%cache_db,'GDBM_File',$cache_filename,&GDBM_WRCREAT(),0640)) {
  838:         my $storestring = freeze(\%cache);
  839:         $cache_db{$key}=$storestring;
  840:         $cache_db{$key.'.time'}=time;
  841:         untie(%cache_db);
  842:     }
  843:     undef(%cache);
  844:     undef($current_symb);
  845:     undef($cache_filename);
  846:     return;
  847: }
  848: 
  849: #####################################################
  850: #####################################################
  851: 
  852: =pod
  853: 
  854: =item &ensure_proper_cache($symb)
  855: 
  856: Called to make sure we have the proper cache set up.  This is called
  857: prior to every analysis lookup.
  858: 
  859: =cut
  860: 
  861: #####################################################
  862: #####################################################
  863: sub ensure_proper_cache {
  864:     my ($symb) = @_;
  865:     my $cid = $env{'request.course.id'};
  866:     my $new_filename =  '/home/httpd/perl/tmp/'.
  867:         'problemanalysis_'.$cid.'_analysis_cache.db';
  868:     if (! defined($cache_filename) ||
  869:         $cache_filename ne $new_filename ||
  870:         ! defined($current_symb)   ||
  871:         $current_symb ne $symb) {
  872:         $cache_filename = $new_filename;
  873:         # Notice: $current_symb is not set to $symb until after the cache is
  874:         # loaded.  This is what tells &load_analysis_cache to load in a new
  875:         # symb cache.
  876:         &load_analysis_cache($symb);
  877:         $current_symb = $symb;
  878:     }
  879: }
  880: 
  881: #####################################################
  882: #####################################################
  883: 
  884: =pod
  885: 
  886: =item &store_analysis($sname,$sdom,$symb,$partid,$respid,$dataset)
  887: 
  888: Stores the analysis data in the in memory cache.
  889: 
  890: =cut
  891: 
  892: #####################################################
  893: #####################################################
  894: sub store_analysis {
  895:     my ($sname,$sdom,$symb,$dataset) = @_;
  896:     return if ($symb ne $current_symb);
  897:     $cache{$sname.':'.$sdom}=$dataset;
  898:     return;
  899: }
  900: 
  901: }
  902: #####################################################
  903: #####################################################
  904: 
  905: =pod
  906: 
  907: =back
  908: 
  909: =cut
  910: 
  911: #####################################################
  912: #####################################################
  913: 
  914: ##
  915: ## The following is copied from datecalc1.pl, part of the 
  916: ## Spreadsheet::WriteExcel CPAN module.
  917: ##
  918: ##
  919: ######################################################################
  920: #
  921: # Demonstration of writing date/time cells to Excel spreadsheets,
  922: # using UNIX/Perl time as source of date/time.
  923: #
  924: # Copyright 2000, Andrew Benham, adsb@bigfoot.com
  925: #
  926: ######################################################################
  927: #
  928: # UNIX/Perl time is the time since the Epoch (00:00:00 GMT, 1 Jan 1970)
  929: # measured in seconds.
  930: #
  931: # An Excel file can use exactly one of two different date/time systems.
  932: # In these systems, a floating point number represents the number of days
  933: # (and fractional parts of the day) since a start point. The floating point
  934: # number is referred to as a 'serial'.
  935: # The two systems ('1900' and '1904') use different starting points:
  936: #  '1900'; '1.00' is 1 Jan 1900 BUT 1900 is erroneously regarded as
  937: #          a leap year - see:
  938: #            http://support.microsoft.com/support/kb/articles/Q181/3/70.asp
  939: #          for the excuse^H^H^H^H^H^Hreason.
  940: #  '1904'; '1.00' is 2 Jan 1904.
  941: #
  942: # The '1904' system is the default for Apple Macs. Windows versions of
  943: # Excel have the option to use the '1904' system.
  944: #
  945: # Note that Visual Basic's "DateSerial" function does NOT erroneously
  946: # regard 1900 as a leap year, and thus its serials do not agree with
  947: # the 1900 serials of Excel for dates before 1 Mar 1900.
  948: #
  949: # Note that StarOffice (at least at version 5.2) does NOT erroneously
  950: # regard 1900 as a leap year, and thus its serials do not agree with
  951: # the 1900 serials of Excel for dates before 1 Mar 1900.
  952: #
  953: ######################################################################
  954: #
  955: # Calculation description
  956: # =======================
  957: #
  958: # 1900 system
  959: # -----------
  960: # Unix time is '0' at 00:00:00 GMT 1 Jan 1970, i.e. 70 years after 1 Jan 1900.
  961: # Of those 70 years, 17 (1904,08,12,16,20,24,28,32,36,40,44,48,52,56,60,64,68)
  962: # were leap years with an extra day.
  963: # Thus there were 17 + 70*365 days = 25567 days between 1 Jan 1900 and
  964: # 1 Jan 1970.
  965: # In the 1900 system, '1' is 1 Jan 1900, but as 1900 was not a leap year
  966: # 1 Jan 1900 should really be '2', so 1 Jan 1970 is '25569'.
  967: #
  968: # 1904 system
  969: # -----------
  970: # Unix time is '0' at 00:00:00 GMT 1 Jan 1970, i.e. 66 years after 1 Jan 1904.
  971: # Of those 66 years, 17 (1904,08,12,16,20,24,28,32,36,40,44,48,52,56,60,64,68)
  972: # were leap years with an extra day.
  973: # Thus there were 17 + 66*365 days = 24107 days between 1 Jan 1904 and
  974: # 1 Jan 1970.
  975: # In the 1904 system, 2 Jan 1904 being '1', 1 Jan 1970 is '24107'.
  976: #
  977: ######################################################################
  978: #
  979: # Copyright (c) 2000, Andrew Benham.
  980: # This program is free software. It may be used, redistributed and/or
  981: # modified under the same terms as Perl itself.
  982: #
  983: # Andrew Benham, adsb@bigfoot.com
  984: # London, United Kingdom
  985: # 11 Nov 2000
  986: #
  987: ######################################################################
  988: #-----------------------------------------------------------
  989: # calc_serial()
  990: #
  991: # Called with (up to) 2 parameters.
  992: #   1.  Unix timestamp.  If omitted, uses current time.
  993: #   2.  GMT flag. Set to '1' to return serial in GMT.
  994: #       If omitted, returns serial in appropriate timezone.
  995: #
  996: # Returns date/time serial according to $DATE_SYSTEM selected
  997: #-----------------------------------------------------------
  998: sub calc_serial {
  999:     # Use 1900 date system on all platforms other than Apple Mac (for which
 1000:     # use 1904 date system).
 1001:     my $DATE_SYSTEM = ($^O eq 'MacOS') ? 1 : 0;
 1002:     my $time = (defined $_[0]) ? $_[0] : time();
 1003:     my $gmtflag = (defined $_[1]) ? $_[1] : 0;
 1004:     #
 1005:     # Divide timestamp by number of seconds in a day.
 1006:     # This gives a date serial with '0' on 1 Jan 1970.
 1007:     my $serial = $time / 86400;
 1008:     #
 1009:     # Adjust the date serial by the offset appropriate to the
 1010:     # currently selected system (1900/1904).
 1011:     if ($DATE_SYSTEM == 0) {        # use 1900 system
 1012:         $serial += 25569;
 1013:     } else {                        # use 1904 system
 1014:         $serial += 24107;
 1015:     }
 1016:     #
 1017:     unless ($gmtflag) {
 1018:         # Now have a 'raw' serial with the right offset. But this
 1019:         # gives a serial in GMT, which is false unless the timezone
 1020:         # is GMT. We need to adjust the serial by the appropriate
 1021:         # timezone offset.
 1022:         # Calculate the appropriate timezone offset by seeing what
 1023:         # the differences between localtime and gmtime for the given
 1024:         # time are.
 1025:         #    
 1026:         my @gmtime = gmtime($time);
 1027:         my @ltime  = localtime($time);
 1028:         #
 1029:         # For the first 7 elements of the two arrays, adjust the
 1030:         # date serial where the elements differ.
 1031:         for (0 .. 6) {
 1032:             my $diff = $ltime[$_] - $gmtime[$_];
 1033:             if ($diff) {
 1034:                 $serial += _adjustment($diff,$_);
 1035:             }
 1036:         }
 1037:     }
 1038:     #
 1039:     # Perpetuate the error that 1900 was a leap year by decrementing
 1040:     # the serial if we're using the 1900 system and the date is prior to
 1041:     # 1 Mar 1900. This has the effect of making serial value '60'
 1042:     # 29 Feb 1900.
 1043:     #
 1044:     # This fix only has any effect if UNIX/Perl time on the platform
 1045:     # can represent 1900. Many can't.
 1046:     #
 1047:     unless ($DATE_SYSTEM) {
 1048:         $serial-- if ($serial < 61);    # '61' is 1 Mar 1900
 1049:     }
 1050:     return $serial;
 1051: }
 1052: 
 1053: sub _adjustment {
 1054:     # Based on the difference in the localtime/gmtime array elements
 1055:     # number, return the adjustment required to the serial.
 1056:     #
 1057:     # We only look at some elements of the localtime/gmtime arrays:
 1058:     #    seconds    unlikely to be different as all known timezones
 1059:     #               have an offset of integral multiples of 15 minutes,
 1060:     #               but it's easy to do.
 1061:     #    minutes    will be different for timezone offsets which are
 1062:     #               not an exact number of hours.
 1063:     #    hours      very likely to be different.
 1064:     #    weekday    will differ when localtime/gmtime difference
 1065:     #               straddles midnight.
 1066:     #
 1067:     # Assume that difference between localtime and gmtime is less than
 1068:     # 5 days, then don't have to do maths for day of month, month number,
 1069:     # year number, etc...
 1070:     #
 1071:     my ($delta,$element) = @_;
 1072:     my $adjust = 0;
 1073:     #
 1074:     if ($element == 0) {            # Seconds
 1075:         $adjust = $delta/86400;         # 60 * 60 * 24
 1076:     } elsif ($element == 1) {       # Minutes
 1077:         $adjust = $delta/1440;          # 60 * 24
 1078:     } elsif ($element == 2) {       # Hours
 1079:         $adjust = $delta/24;            # 24
 1080:     } elsif ($element == 6) {       # Day of week number
 1081:         # Catch difference straddling Sat/Sun in either direction
 1082:         $delta += 7 if ($delta < -4);
 1083:         $delta -= 7 if ($delta > 4);
 1084:         #    
 1085:         $adjust = $delta;
 1086:     }
 1087:     return $adjust;
 1088: }
 1089: 
 1090: ###########################################################
 1091: ###########################################################
 1092: 
 1093: =pod
 1094: 
 1095: =item get_problem_data
 1096: 
 1097: Returns a data structure describing the problem.
 1098: 
 1099: Inputs: $url
 1100: 
 1101: Returns: %Partdata
 1102: 
 1103: =cut
 1104: 
 1105: ## note: we must force each foil and option to not begin or end with
 1106: ##       spaces as they are stored without such data.
 1107: ##
 1108: ###########################################################
 1109: ###########################################################
 1110: sub get_problem_data {
 1111:     my ($url) = @_;
 1112:     my $Answ=&Apache::lonnet::ssi($url,('grade_target' => 'analyze'));
 1113:     (my $garbage,$Answ)=split(/_HASH_REF__/,$Answ,2);
 1114:     my %Answer;
 1115:     %Answer=&Apache::lonnet::str2hash($Answ);
 1116:     my %Partdata;
 1117:     foreach my $part (@{$Answer{'parts'}}) {
 1118:         while (my($key,$value) = each(%Answer)) {
 1119:             #
 1120:             # Logging code:
 1121:             if (0) {
 1122:                 &Apache::lonnet::logthis($part.' got key "'.$key.'"');
 1123:                 if (ref($value) eq 'ARRAY') {
 1124:                     &Apache::lonnet::logthis('    @'.join(',',@$value));
 1125:                 } else {
 1126:                     &Apache::lonnet::logthis('    '.$value);
 1127:                 }
 1128:             }
 1129:             # End of logging code
 1130:             next if ($key !~ /^$part/);
 1131:             $key =~ s/^$part\.//;
 1132:             if (ref($value) eq 'ARRAY') {
 1133:                 if ($key eq 'options') {
 1134:                     $Partdata{$part}->{'_Options'}=$value;
 1135:                 } elsif ($key eq 'concepts') {
 1136:                     $Partdata{$part}->{'_Concepts'}=$value;
 1137:                 } elsif ($key eq 'items') {
 1138:                     $Partdata{$part}->{'_Items'}=$value;
 1139:                 } elsif ($key =~ /^concept\.(.*)$/) {
 1140:                     my $concept = $1;
 1141:                     foreach my $foil (@$value) {
 1142:                         $Partdata{$part}->{'_Foils'}->{$foil}->{'_Concept'}=
 1143:                                                                       $concept;
 1144:                     }
 1145:                 } elsif ($key =~ /^(unit|incorrect|answer|ans_low|ans_high|str_type)$/) {
 1146:                     $Partdata{$part}->{$key}=$value;
 1147:                 }
 1148:             } else {
 1149:                 if ($key=~ /^foil\.text\.(.*)$/) {
 1150:                     my $foil = $1;
 1151:                     $Partdata{$part}->{'_Foils'}->{$foil}->{'name'}=$foil;
 1152:                     $value =~ s/(\s*$|^\s*)//g;
 1153:                     $Partdata{$part}->{'_Foils'}->{$foil}->{'text'}=$value;
 1154:                 } elsif ($key =~ /^foil\.value\.(.*)$/) {
 1155:                     my $foil = $1;
 1156:                     $Partdata{$part}->{'_Foils'}->{$foil}->{'value'}=$value;
 1157:                 } elsif ($key eq 'answercomputed') {
 1158:                     $Partdata{$part}->{'answercomputed'} = $value;
 1159:                 }
 1160:             }
 1161:         }
 1162:     }
 1163:     # Further debugging code
 1164:     if (0) {
 1165:         &Apache::lonnet::logthis('lonstathelpers::get_problem_data');
 1166:         &log_hash_ref(\%Partdata);
 1167:     }
 1168:     return %Partdata;
 1169: }
 1170: 
 1171: sub log_array_ref {
 1172:     my ($arrayref,$prefix) = @_;
 1173:     return if (ref($arrayref) ne 'ARRAY');
 1174:     if (! defined($prefix)) { $prefix = ''; };
 1175:     foreach my $v (@$arrayref) {
 1176:         if (ref($v) eq 'ARRAY') {
 1177:             &log_array_ref($v,$prefix.'  ');
 1178:         } elsif (ref($v) eq 'HASH') {
 1179:             &log_hash_ref($v,$prefix.'  ');
 1180:         } else {
 1181:             &Apache::lonnet::logthis($prefix.'"'.$v.'"');
 1182:         }
 1183:     }
 1184: }
 1185: 
 1186: sub log_hash_ref {
 1187:     my ($hashref,$prefix) = @_;
 1188:     return if (ref($hashref) ne 'HASH');
 1189:     if (! defined($prefix)) { $prefix = ''; };
 1190:     while (my ($k,$v) = each(%$hashref)) {
 1191:         if (ref($v) eq 'ARRAY') {
 1192:             &Apache::lonnet::logthis($prefix.'"'.$k.'" = array');
 1193:             &log_array_ref($v,$prefix.'  ');
 1194:         } elsif (ref($v) eq 'HASH') {
 1195:             &Apache::lonnet::logthis($prefix.'"'.$k.'" = hash');
 1196:             &log_hash_ref($v,$prefix.'  ');
 1197:         } else {
 1198:             &Apache::lonnet::logthis($prefix.'"'.$k.'" => "'.$v.'"');
 1199:         }
 1200:     }
 1201: }
 1202: ####################################################
 1203: ####################################################
 1204: 
 1205: =pod
 1206: 
 1207: =item &limit_by_time()
 1208: 
 1209: =cut
 1210: 
 1211: ####################################################
 1212: ####################################################
 1213: sub limit_by_time_form {
 1214:     my $Starttime_form = '';
 1215:     my $starttime = &Apache::lonhtmlcommon::get_date_from_form
 1216:         ('limitby_startdate');
 1217:     my $endtime = &Apache::lonhtmlcommon::get_date_from_form
 1218:         ('limitby_enddate');
 1219:     if (! defined($endtime)) {
 1220:         $endtime = time;
 1221:     }
 1222:     if (! defined($starttime)) {
 1223:         $starttime = $endtime - 60*60*24*7;
 1224:     }
 1225:     my $state;
 1226:     if (&limit_by_time()) {
 1227:         $state = '';
 1228:     } else {
 1229:         $state = 'disabled';
 1230:     }
 1231:     my $startdateform = &Apache::lonhtmlcommon::date_setter
 1232:         ('Statistics','limitby_startdate',$starttime,undef,undef,$state);
 1233:     my $enddateform = &Apache::lonhtmlcommon::date_setter
 1234:         ('Statistics','limitby_enddate',$endtime,undef,undef,$state);
 1235:     my $Str;
 1236:     $Str .= '<script language="Javascript" >';
 1237:     $Str .= 'function toggle_limitby_activity(state) {';
 1238:     $Str .= '    if (state) {';
 1239:     $Str .= '        limitby_startdate_enable();';
 1240:     $Str .= '        limitby_enddate_enable();';
 1241:     $Str .= '    } else {';
 1242:     $Str .= '        limitby_startdate_disable();';
 1243:     $Str .= '        limitby_enddate_disable();';
 1244:     $Str .= '    }';    
 1245:     $Str .= '}';
 1246:     $Str .= '</script>';
 1247:     $Str .= '<fieldset>';
 1248:     my $timecheckbox = '<input type="checkbox" name="limit_by_time" ';
 1249:     if (&limit_by_time()) {
 1250:         $timecheckbox .= ' checked ';
 1251:     } 
 1252:     $timecheckbox .= 'OnChange="javascript:toggle_limitby_activity(this.checked);" ';
 1253:     $timecheckbox .= ' />';
 1254:     $Str .= '<legend>'.&mt('[_1] Limit by time',$timecheckbox).'</legend>';
 1255:     $Str .= &mt('Start Time: [_1]',$startdateform).'<br />';
 1256:     $Str .= &mt('&nbsp;End Time: [_1]',$enddateform).'<br />';
 1257:     $Str .= '</fieldset>';
 1258:     return $Str;
 1259: }
 1260: 
 1261: sub limit_by_time {
 1262:     if (exists($env{'form.limit_by_time'}) &&
 1263:         $env{'form.limit_by_time'} ne '' ) {
 1264:         return 1;
 1265:     } else {
 1266:         return 0;
 1267:     }
 1268: }
 1269: 
 1270: sub get_time_limits {
 1271:     my $starttime = &Apache::lonhtmlcommon::get_date_from_form
 1272:         ('limitby_startdate');
 1273:     my $endtime = &Apache::lonhtmlcommon::get_date_from_form
 1274:         ('limitby_enddate');
 1275:     return ($starttime,$endtime);
 1276: }
 1277: 
 1278: ####################################################
 1279: ####################################################
 1280: 
 1281: =pod
 1282: 
 1283: =item &manage_caches
 1284: 
 1285: Inputs: $r, apache request object
 1286: 
 1287: Returns: An array of scalars containing html for buttons.
 1288: 
 1289: =cut
 1290: 
 1291: ####################################################
 1292: ####################################################
 1293: sub manage_caches {
 1294:     my ($r,$formname,$inputname,$update_message) = @_;
 1295:     &Apache::loncoursedata::clear_internal_caches();
 1296:     my $sectionkey = 
 1297:         join(',',
 1298:              map {
 1299:                      &Apache::lonnet::escape($_);
 1300:                  } sort(&Apache::lonstatistics::get_selected_sections())
 1301:              );
 1302:     my $statuskey = $Apache::lonstatistics::enrollment_status;
 1303:     if (exists($env{'form.ClearCache'}) || 
 1304:         exists($env{'form.updatecaches'}) || 
 1305:         (exists($env{'form.firstrun'}) && $env{'form.firstrun'} ne 'no') ||
 1306:         (exists($env{'form.prevsection'}) &&
 1307:             $env{'form.prevsection'} ne $sectionkey) ||
 1308:         (exists($env{'form.prevenrollstatus'}) &&
 1309:             $env{'form.prevenrollstatus'} ne $statuskey)
 1310:         ) {
 1311:         if (defined($update_message)) {
 1312:             $r->print($update_message);
 1313:         }
 1314:         if (0) {
 1315:             &Apache::lonnet::logthis('Updating mysql student data caches');
 1316:         }
 1317:         &gather_full_student_data($r,$formname,$inputname);
 1318:     }
 1319:     #
 1320:     my @Buttons = 
 1321:         ('<input type="submit" name="ClearCache" '.
 1322:              'value="'.&mt('Clear Caches').'" />',
 1323:          '<input type="submit" name="updatecaches" '.
 1324:              'value="'.&mt('Update Caches').'" />'.
 1325:          &Apache::loncommon::help_open_topic('Statistics_Cache'),
 1326:          '<input type="hidden" name="prevsection" value="'.$sectionkey.'" />',
 1327:          '<input type="hidden" name="prevenrollstatus" value="'.$statuskey.'" />'
 1328:          );
 1329:     #
 1330:     if (! exists($env{'form.firstrun'})) {
 1331:         $r->print('<input type="hidden" name="firstrun" value="yes" />');
 1332:     } else {
 1333:         $r->print('<input type="hidden" name="firstrun" value="no" />');
 1334:     }
 1335:     #
 1336:     return @Buttons;
 1337: }
 1338: 
 1339: sub gather_full_student_data {
 1340:     my ($r,$formname,$inputname) = @_;
 1341:     my $status_type;
 1342:     if (defined($formname)) {
 1343:         $status_type = 'inline';
 1344:     } else {
 1345:         $status_type = 'popup';
 1346:     }
 1347:     my $c = $r->connection();
 1348:     #
 1349:     &Apache::loncoursedata::clear_internal_caches();
 1350:     #
 1351:     my @Students = @Apache::lonstatistics::Students;
 1352:     #
 1353:     # Open the progress window
 1354:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
 1355:         ($r,&mt('Student Data Compilation Status'),
 1356:          &mt('Student Data Compilation Progress'), scalar(@Students),
 1357:          $status_type,undef,$formname,$inputname);
 1358:     #
 1359:     while (my $student = shift @Students) {
 1360:         return if ($c->aborted());
 1361:         my $status = &Apache::loncoursedata::ensure_current_full_data
 1362:             ($student->{'username'},$student->{'domain'},
 1363:              $env{'request.course.id'});
 1364:         &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 1365:                                                  &mt('last student'));
 1366:     }
 1367:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 1368:     $r->rflush();
 1369:     return;
 1370: }
 1371: 
 1372: ####################################################
 1373: ####################################################
 1374: 
 1375: =pod
 1376: 
 1377: =item &submission_report_form
 1378: 
 1379: Input: The originating reportSelected value for the current stats page.
 1380: 
 1381: Output: Scalar containing HTML with needed form elements and a link to 
 1382: the student submission reports page.
 1383: 
 1384: =cut
 1385: 
 1386: ####################################################
 1387: ####################################################
 1388: sub submission_report_form {
 1389:     my ($original_report) = @_;
 1390:     # Note: In the link below we change the reportSelected value.  If
 1391:     # the user hits the 'back' button on the browser after getting their
 1392:     # student submissions report, this value may still be around.  So we
 1393:     # output a script block to set it properly.  If the $original_report
 1394:     # value is unset, you are just asking for trouble.
 1395:     if (! defined($original_report)) {
 1396:         &Apache::lonnet::logthis
 1397:             ('someone called lonstathelpers::submission_report_form without '.
 1398:              ' enough input.');
 1399:     }
 1400:     my $html = $/.
 1401:         '<script type="Text/JavaScript">'.
 1402:         "document.Statistics.reportSelected.value='$original_report';".
 1403:         '</script>'.
 1404:         '<input type="hidden" name="correctans" value="true" />'.
 1405:         '<input type="hidden" name="prob_status" value="true" />'.
 1406:         '<input type="hidden" name="all_sub" value="true" />';
 1407:     my $output_selector = $/.'<select name="output">'.$/;
 1408:     foreach ('HTML','Excel','CSV') {
 1409:         $output_selector .= '    <option value="'.lc($_).'"';
 1410:         if ($env{'form.output'} eq lc($_)) {
 1411:             $output_selector .= ' selected ';
 1412:         }
 1413:         $output_selector .='>'.&mt($_).'</option>'.$/;
 1414:     } 
 1415:     $output_selector .= '</select>'.$/;
 1416:     my $link = '<a href="javascript:'.
 1417:        q{document.Statistics.reportSelected.value='student_submission_reports';}.
 1418:        'document.Statistics.submit();">';
 1419:     $html.= &mt('View data as [_1] [_2]go[_3]',$output_selector,
 1420:                 $link,'</a>').$/;
 1421:     return $html
 1422: }
 1423: 
 1424: ####################################################
 1425: ####################################################
 1426: 
 1427: =pod
 1428: 
 1429: =back
 1430: 
 1431: =cut
 1432: 
 1433: ####################################################
 1434: ####################################################
 1435: 
 1436: 1;
 1437: 
 1438: __END__

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