File:  [LON-CAPA] / loncom / interface / statistics / lonstathelpers.pm
Revision 1.78: download - view: text, annotated - select for diffs
Mon Sep 7 02:25:32 2020 UTC (3 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- problem selector for grading
  - use rowspan for multiple responseIDs for each part in multipart problems,
    and add missing <tr> start tags.

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

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