File:  [LON-CAPA] / loncom / interface / statistics / lonstathelpers.pm
Revision 1.70: download - view: text, annotated - select for diffs
Thu Jun 21 13:46:10 2012 UTC (12 years ago) by goltermann
Branches: MAIN
CVS tags: HEAD
consistent layout for problem view

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

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