File:  [LON-CAPA] / loncom / interface / statistics / lonstathelpers.pm
Revision 1.60: download - view: text, annotated - select for diffs
Sun Feb 28 23:58:55 2010 UTC (14 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6119 Anonymous surveys.

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

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