File:  [LON-CAPA] / loncom / interface / statistics / lonstathelpers.pm
Revision 1.76.2.2: download - view: text, annotated - select for diffs
Tue Sep 1 15:11:02 2020 UTC (3 years, 9 months ago) by raeburn
Branches: version_2_11_X
- For 2.11
  Backport 1.77

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

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