File:  [LON-CAPA] / loncom / interface / statistics / lonstathelpers.pm
Revision 1.67: download - view: text, annotated - select for diffs
Mon Jul 4 09:25:02 2011 UTC (12 years, 11 months ago) by foxr
Branches: MAIN
CVS tags: language_hyphenation_merge, language_hyphenation, HEAD
Centralize knowledge of where the tmp directory is within LONCAPA.pm

    1: # The LearningOnline Network with CAPA
    2: #
    3: # $Id: lonstathelpers.pm,v 1.67 2011/07/04 09:25:02 foxr Exp $
    4: #
    5: # Copyright Michigan State University Board of Trustees
    6: #
    7: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    8: #
    9: # LON-CAPA is free software; you can redistribute it and/or modify
   10: # it under the terms of the GNU General Public License as published by
   11: # the Free Software Foundation; either version 2 of the License, or
   12: # (at your option) any later version.
   13: #
   14: # LON-CAPA is distributed in the hope that it will be useful,
   15: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   16: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   17: # GNU General Public License for more details.
   18: #
   19: # You should have received a copy of the GNU General Public License
   20: # along with LON-CAPA; if not, write to the Free Software
   21: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   22: #
   23: # /home/httpd/html/adm/gpl.txt
   24: #
   25: # http://www.lon-capa.org/
   26: #
   27: ####################################################
   28: ####################################################
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonstathelpers - helper routines used by statistics
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This module provides a place to consolidate much of the statistics 
   39: routines that are needed across multiple statistics functions.
   40: 
   41: =head1 OVERVIEW
   42: 
   43: =over 4
   44: 
   45: =cut
   46: 
   47: ####################################################
   48: ####################################################
   49: package Apache::lonstathelpers;
   50: 
   51: use strict;
   52: use Apache::lonnet;
   53: use Apache::loncommon();
   54: use Apache::lonhtmlcommon();
   55: use Apache::loncoursedata();
   56: use Apache::lonstatistics;
   57: use Apache::lonlocal;
   58: use HTML::Entities();
   59: use Time::Local();
   60: use Spreadsheet::WriteExcel();
   61: use GDBM_File;
   62: use Storable qw(freeze thaw);
   63: use lib '/home/httpd/lib/perl/';
   64: use LONCAPA;
   65:  
   66: 
   67: ####################################################
   68: ####################################################
   69: 
   70: =pod
   71: 
   72: =item &render_resource($resource)
   73: 
   74: Input: a navmaps resource
   75: 
   76: Retunrs: a scalar containing html for a rendering of the problem
   77: within a table.
   78: 
   79: =cut
   80: 
   81: ####################################################
   82: ####################################################
   83: sub render_resource {
   84:     my ($resource) = @_;
   85:     ##
   86:     ## Render the problem
   87:     my ($base) = ($resource->src =~ m|^(.*/)[^/]*$|);
   88:     $base="http://".$ENV{'SERVER_NAME'}.$base;
   89:     my ($src,$symb)=($resource->link,&escape($resource->shown_symb));
   90:     my $rendered_problem = &Apache::lonnet::ssi_body($src.'?symb='.$symb);
   91:     $rendered_problem =~ s/<\s*form\s*/<nop /g;
   92:     $rendered_problem =~ s|(<\s*/form\s*>)|<\/nop>|g;
   93:     return '<table bgcolor="ffffff"><tr><td>'.
   94:         '<base href="'.$base.'" />'.
   95:         $rendered_problem.
   96:         '</td></tr></table>';
   97: }
   98: 
   99: ####################################################
  100: ####################################################
  101: 
  102: =pod
  103: 
  104: =item &get_resources
  105: 
  106: =cut
  107: 
  108: ####################################################
  109: ####################################################
  110: sub get_resources {
  111:     my ($navmap,$sequence) = @_;
  112:     my @resources = $navmap->retrieveResources($sequence,
  113:                                                sub { shift->is_problem(); },
  114:                                                0,0,0);
  115:     return @resources;
  116: }
  117: 
  118: ####################################################
  119: ####################################################
  120: 
  121: =pod
  122: 
  123: =item &problem_selector($AcceptedResponseTypes)
  124: 
  125: Input: scalar containing regular expression which matches response
  126: types to show.  '.' will yield all, '(option|radiobutton)' will match
  127: all option response and radiobutton problems.
  128: 
  129: Returns: A string containing html for a table which lists the sequences
  130: and their contents.  A radiobutton is provided for each problem.
  131: Skips 'survey' problems.
  132: 
  133: =cut
  134: 
  135: ####################################################
  136: ####################################################
  137: sub problem_selector {
  138:     my ($AcceptedResponseTypes,$sequence_addendum,$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
  720:         ($r,'Student Answer Compilation Status',
  721:          'Student Answer Compilation Progress', scalar(@$Students),
  722:          $status_type,undef,$formname,$inputname);
  723:     $r->rflush();
  724:     foreach my $student (@$Students) {
  725:         last if ($c->aborted());
  726:         my $sname = $student->{'username'};
  727:         my $sdom = $student->{'domain'};
  728:         my $answer = &Apache::lonstathelpers::get_student_answer
  729:             ($resource,$sname,$sdom,$partid,$respid);
  730:         &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
  731:                                                      'last student');
  732:         $answers{$answer}++;
  733:         $student->{'answer'} = $answer;
  734:     }
  735:     &Apache::lonstathelpers::write_analysis_cache();
  736:     return if ($c->aborted());
  737:     $r->rflush();
  738:     # close progress window
  739:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
  740:     return \%answers;
  741: }
  742: 
  743: #####################################################
  744: #####################################################
  745: 
  746: =pod
  747: 
  748: =item analyze_problem_as_student
  749: 
  750: Analyzes a homework problem for a student
  751: 
  752: Inputs: $resource: a resource object
  753:         $sname, $sdom, $partid, $respid
  754: 
  755: Returns: the problem analysis hash
  756: 
  757: =cut
  758: 
  759: #####################################################
  760: #####################################################
  761: sub analyze_problem_as_student {
  762:     my ($resource,$sname,$sdom) = @_;
  763:     if (ref($resource) ne 'HASH') {
  764:         my $res = $resource;
  765:         $resource = { 'src' => $res->src,
  766:                       'symb' => $res->symb,
  767:                       'parts' => $res->parts };
  768:         foreach my $part (@{$resource->{'parts'}}) {
  769:             $resource->{'partdata'}->{$part}->{'ResponseIds'}=
  770:                 [$res->responseIds($part)];
  771:         }
  772:     }
  773:     my $url = $resource->{'src'};
  774:     my $symb = $resource->{'symb'};
  775:     my $analysis = &get_from_analysis_cache($sname,$sdom,$symb);
  776:     if (! defined($analysis)) {
  777:         my $courseid = $env{'request.course.id'};
  778:         my $Answ=&Apache::lonnet::ssi($url,('grade_target' => 'analyze',
  779:                                             'grade_domain' => $sdom,
  780:                                             'grade_username' => $sname,
  781:                                             'grade_symb' => $symb,
  782:                                             'grade_courseid' => $courseid));
  783:         (my $garbage,$analysis)=split(/_HASH_REF__/,$Answ,2);
  784:         &store_analysis($sname,$sdom,$symb,$analysis);
  785:     }
  786:     my %Answer=&Apache::lonnet::str2hash($analysis);
  787:     #
  788:     return \%Answer;
  789: }
  790: 
  791: #####################################################
  792: #####################################################
  793: 
  794: =pod
  795: 
  796: =item get_student_answer
  797: 
  798: Analyzes a homework problem for a particular student and returns the correct 
  799: answer.  Attempts to put together an answer for problem types 
  800: that do not natively support it.
  801: 
  802: Inputs: $resource: a resource object (from navmaps or hash from loncoursedata)
  803:         $sname, $sdom, $partid, $respid
  804: 
  805: Returns: $answer
  806: 
  807: If $partid and $respid are specified, $answer is simply a scalar containing
  808: the correct answer for the response.
  809: 
  810: If $partid or $respid are undefined, $answer will be a hash reference with
  811: keys $partid.'.'.$respid.'.answer'.
  812: 
  813: =cut
  814: 
  815: #####################################################
  816: #####################################################
  817: sub get_student_answer {
  818:     my ($resource,$sname,$sdom,$partid,$respid) = @_;
  819:     #
  820:     if (ref($resource) ne 'HASH') {
  821:         my $res = $resource;
  822:         $resource = { 'src' => $res->src,
  823:                       'symb' => $res->symb,
  824:                       'parts' => $res->parts };
  825:         foreach my $part (@{$resource->{'parts'}}) {
  826:             $resource->{'partdata'}->{$part}->{'ResponseIds'}=
  827:                 [$res->responseIds($part)];
  828:         }
  829:     }
  830:     #
  831:     my $analysis = 
  832:         &analyze_problem_as_student($resource,$sname,$sdom);
  833:     my $answer;
  834:     foreach my $partid (@{$resource->{'parts'}}) {
  835:         my $partdata = $resource->{'partdata'}->{$partid};
  836:         foreach my $respid (@{$partdata->{'ResponseIds'}}) {
  837:             my $prefix = $partid.'.'.$respid;
  838:             my $key = $prefix.'.answer';
  839:             $answer->{$partid}->{$respid} = 
  840:                 &get_answer($prefix,$key,%$analysis);
  841:         }
  842:     }
  843:     my $returnvalue;
  844:     if (! defined($partid)) {
  845:         $returnvalue = $answer;
  846:     } elsif (! defined($respid)) {
  847:         $returnvalue = $answer->{$partid};
  848:     } else {
  849:         $returnvalue = $answer->{$partid}->{$respid};
  850:     }
  851:     return $returnvalue;
  852: }
  853: 
  854: sub get_answer {
  855:     my ($prefix,$key,%Answer) = @_;
  856:     my $returnvalue;
  857:     if (exists($Answer{$key})) {
  858: 	if (ref($Answer{$key}) eq 'HASH') {
  859: 	    my $which = 'INTERNAL';
  860: 	    if (!exists($Answer{$key}{$which})) {
  861: 		$which = (sort(keys(%{ $Answer{$key} })))[0];
  862: 	    }
  863: 	    my $student_answer = $Answer{$key}{$which}[0][0];
  864: 	    $returnvalue = $student_answer; 
  865: 	} else {
  866: 	    &Apache::lonnet::logthis("error analyzing problem. got a answer of type ".ref($Answer{$key}));
  867: 	}
  868:     } else {
  869:         if (exists($Answer{$prefix.'.shown'})) {
  870:             # The response has foils
  871:             my %values;
  872:             while (my ($k,$v) = each(%Answer)) {
  873:                 next if ($k !~ /^$prefix\.foil\.(value|area)\.(.*)$/);
  874:                 my $foilname = $2;
  875:                 $values{$foilname}=$v;
  876:             }
  877:             foreach my $foil (@{$Answer{$prefix.'.shown'}}) {
  878:                 if (ref($values{$foil}) eq 'ARRAY') {
  879:                     $returnvalue.=&HTML::Entities::encode($foil,'<>&"').'='.
  880:                         join(',',map {&HTML::Entities::encode($_,'<>&"')} @{$values{$foil}}).'&';
  881:                 } else {
  882:                     $returnvalue.=&HTML::Entities::encode($foil,'<>&"').'='.
  883:                         &HTML::Entities::encode($values{$foil},'<>&"').'&';
  884:                 }
  885:             }
  886:             $returnvalue =~ s/ /\%20/g;
  887:             chop ($returnvalue);
  888:         }
  889:     }
  890:     return $returnvalue;
  891: }
  892: 
  893: #####################################################
  894: #####################################################
  895: 
  896: =pod
  897: 
  898: =item Caching routines
  899: 
  900: =over 4
  901: 
  902: =item &load_analysis_cache($symb)
  903: 
  904: Loads the cache for the given symb into memory from disk.  
  905: Requires the cache filename be set.  
  906: Only should be called by &ensure_proper_cache.
  907: 
  908: =cut
  909: 
  910: #####################################################
  911: #####################################################
  912: {
  913:     my $cache_filename = undef;
  914:     my $current_symb = undef;
  915:     my %cache;
  916: 
  917: sub load_analysis_cache {
  918:     my ($symb) = @_;
  919:     return if (! defined($cache_filename));
  920:     if (! defined($current_symb) || $current_symb ne $symb) {
  921:         undef(%cache);
  922:         my $storedstring;
  923:         my %cache_db;
  924:         if (tie(%cache_db,'GDBM_File',$cache_filename,&GDBM_READER(),0640)) {
  925:             $storedstring = $cache_db{&escape($symb)};
  926:             untie(%cache_db);
  927:         }
  928:         if (defined($storedstring)) {
  929:             %cache = %{thaw($storedstring)};
  930:         }
  931:     }
  932:     return;
  933: }
  934: 
  935: #####################################################
  936: #####################################################
  937: 
  938: =pod
  939: 
  940: =item &get_from_analysis_cache($sname,$sdom,$symb,$partid,$respid)
  941: 
  942: Returns the appropriate data from the cache, or undef if no data exists.
  943: 
  944: =cut
  945: 
  946: #####################################################
  947: #####################################################
  948: sub get_from_analysis_cache {
  949:     my ($sname,$sdom,$symb) = @_;
  950:     &ensure_proper_cache($symb);
  951:     my $returnvalue;
  952:     if (exists($cache{$sname.':'.$sdom})) {
  953:         $returnvalue = $cache{$sname.':'.$sdom};
  954:     } else {
  955:         $returnvalue = undef;
  956:     }
  957:     return $returnvalue;
  958: }
  959: 
  960: #####################################################
  961: #####################################################
  962: 
  963: =pod
  964: 
  965: =item &write_analysis_cache($symb)
  966: 
  967: Writes the in memory cache to disk so that it can be read in with
  968: &load_analysis_cache($symb).
  969: 
  970: =cut
  971: 
  972: #####################################################
  973: #####################################################
  974: sub write_analysis_cache {
  975:     return if (! defined($current_symb) || ! defined($cache_filename));
  976:     my %cache_db;
  977:     my $key = &escape($current_symb);
  978:     if (tie(%cache_db,'GDBM_File',$cache_filename,&GDBM_WRCREAT(),0640)) {
  979:         my $storestring = freeze(\%cache);
  980:         $cache_db{$key}=$storestring;
  981:         $cache_db{$key.'.time'}=time;
  982:         untie(%cache_db);
  983:     }
  984:     undef(%cache);
  985:     undef($current_symb);
  986:     undef($cache_filename);
  987:     return;
  988: }
  989: 
  990: #####################################################
  991: #####################################################
  992: 
  993: =pod
  994: 
  995: =item &ensure_proper_cache($symb)
  996: 
  997: Called to make sure we have the proper cache set up.  This is called
  998: prior to every analysis lookup.
  999: 
 1000: =cut
 1001: 
 1002: #####################################################
 1003: #####################################################
 1004: sub ensure_proper_cache {
 1005:     my ($symb) = @_;
 1006:     my $cid = $env{'request.course.id'};
 1007:     my $new_filename = LONCAPA::tempdir() .
 1008:         'problemanalysis_'.$cid.'_analysis_cache.db';
 1009:     if (! defined($cache_filename) ||
 1010:         $cache_filename ne $new_filename ||
 1011:         ! defined($current_symb)   ||
 1012:         $current_symb ne $symb) {
 1013:         $cache_filename = $new_filename;
 1014:         # Notice: $current_symb is not set to $symb until after the cache is
 1015:         # loaded.  This is what tells &load_analysis_cache to load in a new
 1016:         # symb cache.
 1017:         &load_analysis_cache($symb);
 1018:         $current_symb = $symb;
 1019:     }
 1020: }
 1021: 
 1022: #####################################################
 1023: #####################################################
 1024: 
 1025: =pod
 1026: 
 1027: =item &store_analysis($sname,$sdom,$symb,$partid,$respid,$dataset)
 1028: 
 1029: Stores the analysis data in the in memory cache.
 1030: 
 1031: =cut
 1032: 
 1033: #####################################################
 1034: #####################################################
 1035: sub store_analysis {
 1036:     my ($sname,$sdom,$symb,$dataset) = @_;
 1037:     return if ($symb ne $current_symb);
 1038:     $cache{$sname.':'.$sdom}=$dataset;
 1039:     return;
 1040: }
 1041: 
 1042: }
 1043: #####################################################
 1044: #####################################################
 1045: 
 1046: =pod
 1047: 
 1048: =back
 1049: 
 1050: =cut
 1051: 
 1052: #####################################################
 1053: #####################################################
 1054: 
 1055: ##
 1056: ## The following is copied from datecalc1.pl, part of the 
 1057: ## Spreadsheet::WriteExcel CPAN module.
 1058: ##
 1059: ##
 1060: ######################################################################
 1061: #
 1062: # Demonstration of writing date/time cells to Excel spreadsheets,
 1063: # using UNIX/Perl time as source of date/time.
 1064: #
 1065: # Copyright 2000, Andrew Benham, adsb@bigfoot.com
 1066: #
 1067: ######################################################################
 1068: #
 1069: # UNIX/Perl time is the time since the Epoch (00:00:00 GMT, 1 Jan 1970)
 1070: # measured in seconds.
 1071: #
 1072: # An Excel file can use exactly one of two different date/time systems.
 1073: # In these systems, a floating point number represents the number of days
 1074: # (and fractional parts of the day) since a start point. The floating point
 1075: # number is referred to as a 'serial'.
 1076: # The two systems ('1900' and '1904') use different starting points:
 1077: #  '1900'; '1.00' is 1 Jan 1900 BUT 1900 is erroneously regarded as
 1078: #          a leap year - see:
 1079: #            http://support.microsoft.com/support/kb/articles/Q181/3/70.asp
 1080: #          for the excuse^H^H^H^H^H^Hreason.
 1081: #  '1904'; '1.00' is 2 Jan 1904.
 1082: #
 1083: # The '1904' system is the default for Apple Macs. Windows versions of
 1084: # Excel have the option to use the '1904' system.
 1085: #
 1086: # Note that Visual Basic's "DateSerial" function does NOT erroneously
 1087: # regard 1900 as a leap year, and thus its serials do not agree with
 1088: # the 1900 serials of Excel for dates before 1 Mar 1900.
 1089: #
 1090: # Note that StarOffice (at least at version 5.2) does NOT erroneously
 1091: # regard 1900 as a leap year, and thus its serials do not agree with
 1092: # the 1900 serials of Excel for dates before 1 Mar 1900.
 1093: #
 1094: ######################################################################
 1095: #
 1096: # Calculation description
 1097: # =======================
 1098: #
 1099: # 1900 system
 1100: # -----------
 1101: # Unix time is '0' at 00:00:00 GMT 1 Jan 1970, i.e. 70 years after 1 Jan 1900.
 1102: # Of those 70 years, 17 (1904,08,12,16,20,24,28,32,36,40,44,48,52,56,60,64,68)
 1103: # were leap years with an extra day.
 1104: # Thus there were 17 + 70*365 days = 25567 days between 1 Jan 1900 and
 1105: # 1 Jan 1970.
 1106: # In the 1900 system, '1' is 1 Jan 1900, but as 1900 was not a leap year
 1107: # 1 Jan 1900 should really be '2', so 1 Jan 1970 is '25569'.
 1108: #
 1109: # 1904 system
 1110: # -----------
 1111: # Unix time is '0' at 00:00:00 GMT 1 Jan 1970, i.e. 66 years after 1 Jan 1904.
 1112: # Of those 66 years, 17 (1904,08,12,16,20,24,28,32,36,40,44,48,52,56,60,64,68)
 1113: # were leap years with an extra day.
 1114: # Thus there were 17 + 66*365 days = 24107 days between 1 Jan 1904 and
 1115: # 1 Jan 1970.
 1116: # In the 1904 system, 2 Jan 1904 being '1', 1 Jan 1970 is '24107'.
 1117: #
 1118: ######################################################################
 1119: #
 1120: # Copyright (c) 2000, Andrew Benham.
 1121: # This program is free software. It may be used, redistributed and/or
 1122: # modified under the same terms as Perl itself.
 1123: #
 1124: # Andrew Benham, adsb@bigfoot.com
 1125: # London, United Kingdom
 1126: # 11 Nov 2000
 1127: #
 1128: ######################################################################
 1129: #-----------------------------------------------------------
 1130: # calc_serial()
 1131: #
 1132: # Called with (up to) 2 parameters.
 1133: #   1.  Unix timestamp.  If omitted, uses current time.
 1134: #   2.  GMT flag. Set to '1' to return serial in GMT.
 1135: #       If omitted, returns serial in appropriate timezone.
 1136: #
 1137: # Returns date/time serial according to $DATE_SYSTEM selected
 1138: #-----------------------------------------------------------
 1139: sub calc_serial {
 1140:     # Use 1900 date system on all platforms other than Apple Mac (for which
 1141:     # use 1904 date system).
 1142:     my $DATE_SYSTEM = ($^O eq 'MacOS') ? 1 : 0;
 1143:     my $time = (defined $_[0]) ? $_[0] : time();
 1144:     my $gmtflag = (defined $_[1]) ? $_[1] : 0;
 1145:     #
 1146:     # Divide timestamp by number of seconds in a day.
 1147:     # This gives a date serial with '0' on 1 Jan 1970.
 1148:     my $serial = $time / 86400;
 1149:     #
 1150:     # Adjust the date serial by the offset appropriate to the
 1151:     # currently selected system (1900/1904).
 1152:     if ($DATE_SYSTEM == 0) {        # use 1900 system
 1153:         $serial += 25569;
 1154:     } else {                        # use 1904 system
 1155:         $serial += 24107;
 1156:     }
 1157:     #
 1158:     unless ($gmtflag) {
 1159:         # Now have a 'raw' serial with the right offset. But this
 1160:         # gives a serial in GMT, which is false unless the timezone
 1161:         # is GMT. We need to adjust the serial by the appropriate
 1162:         # timezone offset.
 1163:         # Calculate the appropriate timezone offset by seeing what
 1164:         # the differences between localtime and gmtime for the given
 1165:         # time are.
 1166:         #    
 1167:         my @gmtime = gmtime($time);
 1168:         my @ltime  = localtime($time);
 1169:         #
 1170:         # For the first 7 elements of the two arrays, adjust the
 1171:         # date serial where the elements differ.
 1172:         for (0 .. 6) {
 1173:             my $diff = $ltime[$_] - $gmtime[$_];
 1174:             if ($diff) {
 1175:                 $serial += _adjustment($diff,$_);
 1176:             }
 1177:         }
 1178:     }
 1179:     #
 1180:     # Perpetuate the error that 1900 was a leap year by decrementing
 1181:     # the serial if we're using the 1900 system and the date is prior to
 1182:     # 1 Mar 1900. This has the effect of making serial value '60'
 1183:     # 29 Feb 1900.
 1184:     #
 1185:     # This fix only has any effect if UNIX/Perl time on the platform
 1186:     # can represent 1900. Many can't.
 1187:     #
 1188:     unless ($DATE_SYSTEM) {
 1189:         $serial-- if ($serial < 61);    # '61' is 1 Mar 1900
 1190:     }
 1191:     return $serial;
 1192: }
 1193: 
 1194: sub _adjustment {
 1195:     # Based on the difference in the localtime/gmtime array elements
 1196:     # number, return the adjustment required to the serial.
 1197:     #
 1198:     # We only look at some elements of the localtime/gmtime arrays:
 1199:     #    seconds    unlikely to be different as all known timezones
 1200:     #               have an offset of integral multiples of 15 minutes,
 1201:     #               but it's easy to do.
 1202:     #    minutes    will be different for timezone offsets which are
 1203:     #               not an exact number of hours.
 1204:     #    hours      very likely to be different.
 1205:     #    weekday    will differ when localtime/gmtime difference
 1206:     #               straddles midnight.
 1207:     #
 1208:     # Assume that difference between localtime and gmtime is less than
 1209:     # 5 days, then don't have to do maths for day of month, month number,
 1210:     # year number, etc...
 1211:     #
 1212:     my ($delta,$element) = @_;
 1213:     my $adjust = 0;
 1214:     #
 1215:     if ($element == 0) {            # Seconds
 1216:         $adjust = $delta/86400;         # 60 * 60 * 24
 1217:     } elsif ($element == 1) {       # Minutes
 1218:         $adjust = $delta/1440;          # 60 * 24
 1219:     } elsif ($element == 2) {       # Hours
 1220:         $adjust = $delta/24;            # 24
 1221:     } elsif ($element == 6) {       # Day of week number
 1222:         # Catch difference straddling Sat/Sun in either direction
 1223:         $delta += 7 if ($delta < -4);
 1224:         $delta -= 7 if ($delta > 4);
 1225:         #    
 1226:         $adjust = $delta;
 1227:     }
 1228:     return $adjust;
 1229: }
 1230: 
 1231: ###########################################################
 1232: ###########################################################
 1233: 
 1234: =pod
 1235: 
 1236: =item get_problem_data
 1237: 
 1238: Returns a data structure describing the problem.
 1239: 
 1240: Inputs: $url
 1241: 
 1242: Returns: %Partdata
 1243: 
 1244: =cut
 1245: 
 1246: ## note: we must force each foil and option to not begin or end with
 1247: ##       spaces as they are stored without such data.
 1248: ##
 1249: ###########################################################
 1250: ###########################################################
 1251: sub get_problem_data {
 1252:     my ($url) = @_;
 1253:     my $Answ=&Apache::lonnet::ssi($url,('grade_target' => 'analyze'));
 1254:     (my $garbage,$Answ)=split(/_HASH_REF__/,$Answ,2);
 1255:     my %Answer;
 1256:     %Answer=&Apache::lonnet::str2hash($Answ);
 1257:     my %Partdata;
 1258:     foreach my $part (@{$Answer{'parts'}}) {
 1259:         while (my($key,$value) = each(%Answer)) {
 1260:             #
 1261:             # Logging code:
 1262:             if (0) {
 1263:                 &Apache::lonnet::logthis($part.' got key "'.$key.'"');
 1264:                 if (ref($value) eq 'ARRAY') {
 1265:                     &Apache::lonnet::logthis('    @'.join(',',@$value));
 1266:                 } else {
 1267:                     &Apache::lonnet::logthis('    '.$value);
 1268:                 }
 1269:             }
 1270:             # End of logging code
 1271:             next if ($key !~ /^\Q$part\E/);
 1272:             $key =~ s/^\Q$part\E\.//;
 1273:             if (ref($value) eq 'ARRAY') {
 1274:                 if ($key eq 'options') {
 1275:                     $Partdata{$part}->{'_Options'}=$value;
 1276:                 } elsif ($key eq 'concepts') {
 1277:                     $Partdata{$part}->{'_Concepts'}=$value;
 1278:                 } elsif ($key eq 'items') {
 1279:                     $Partdata{$part}->{'_Items'}=$value;
 1280:                 } elsif ($key =~ /^concept\.(.*)$/) {
 1281:                     my $concept = $1;
 1282:                     foreach my $foil (@$value) {
 1283:                         $Partdata{$part}->{'_Foils'}->{$foil}->{'_Concept'}=
 1284:                                                                       $concept;
 1285:                     }
 1286:                 } elsif ($key =~ /^(unit|incorrect|answer|ans_low|ans_high|str_type)$/) {
 1287:                     $Partdata{$part}->{$key}=$value;
 1288:                 }
 1289:             } else {
 1290:                 if ($key=~ /^foil\.text\.(.*)$/) {
 1291:                     my $foil = $1;
 1292:                     $Partdata{$part}->{'_Foils'}->{$foil}->{'name'}=$foil;
 1293:                     $value =~ s/(\s*$|^\s*)//g;
 1294:                     $Partdata{$part}->{'_Foils'}->{$foil}->{'text'}=$value;
 1295:                 } elsif ($key =~ /^foil\.value\.(.*)$/) {
 1296:                     my $foil = $1;
 1297:                     $Partdata{$part}->{'_Foils'}->{$foil}->{'value'}=$value;
 1298:                 } elsif ($key eq 'answercomputed') {
 1299:                     $Partdata{$part}->{'answercomputed'} = $value;
 1300:                 }
 1301:             }
 1302:         }
 1303:     }
 1304:     # Further debugging code
 1305:     if (0) {
 1306:         &Apache::lonnet::logthis('lonstathelpers::get_problem_data');
 1307:         &log_hash_ref(\%Partdata);
 1308:     }
 1309:     return %Partdata;
 1310: }
 1311: 
 1312: sub log_array_ref {
 1313:     my ($arrayref,$prefix) = @_;
 1314:     return if (ref($arrayref) ne 'ARRAY');
 1315:     if (! defined($prefix)) { $prefix = ''; };
 1316:     foreach my $v (@$arrayref) {
 1317:         if (ref($v) eq 'ARRAY') {
 1318:             &log_array_ref($v,$prefix.'  ');
 1319:         } elsif (ref($v) eq 'HASH') {
 1320:             &log_hash_ref($v,$prefix.'  ');
 1321:         } else {
 1322:             &Apache::lonnet::logthis($prefix.'"'.$v.'"');
 1323:         }
 1324:     }
 1325: }
 1326: 
 1327: sub log_hash_ref {
 1328:     my ($hashref,$prefix) = @_;
 1329:     return if (ref($hashref) ne 'HASH');
 1330:     if (! defined($prefix)) { $prefix = ''; };
 1331:     while (my ($k,$v) = each(%$hashref)) {
 1332:         if (ref($v) eq 'ARRAY') {
 1333:             &Apache::lonnet::logthis($prefix.'"'.$k.'" = array');
 1334:             &log_array_ref($v,$prefix.'  ');
 1335:         } elsif (ref($v) eq 'HASH') {
 1336:             &Apache::lonnet::logthis($prefix.'"'.$k.'" = hash');
 1337:             &log_hash_ref($v,$prefix.'  ');
 1338:         } else {
 1339:             &Apache::lonnet::logthis($prefix.'"'.$k.'" => "'.$v.'"');
 1340:         }
 1341:     }
 1342: }
 1343: ####################################################
 1344: ####################################################
 1345: 
 1346: =pod
 1347: 
 1348: =item &limit_by_time()
 1349: 
 1350: =cut
 1351: 
 1352: ####################################################
 1353: ####################################################
 1354: sub limit_by_time_form {
 1355:     my $Starttime_form = '';
 1356:     my $starttime = &Apache::lonhtmlcommon::get_date_from_form
 1357:         ('limitby_startdate');
 1358:     my $endtime = &Apache::lonhtmlcommon::get_date_from_form
 1359:         ('limitby_enddate');
 1360:     if (! defined($endtime)) {
 1361:         $endtime = time;
 1362:     }
 1363:     if (! defined($starttime)) {
 1364:         $starttime = $endtime - 60*60*24*7;
 1365:     }
 1366:     my $state;
 1367:     if (&limit_by_time()) {
 1368:         $state = '';
 1369:     } else {
 1370:         $state = 'disabled';
 1371:     }
 1372:     my $startdateform = &Apache::lonhtmlcommon::date_setter
 1373:         ('Statistics','limitby_startdate',$starttime,undef,undef,$state);
 1374:     my $enddateform = &Apache::lonhtmlcommon::date_setter
 1375:         ('Statistics','limitby_enddate',$endtime,undef,undef,$state);
 1376:     my $Str;
 1377:     $Str .= '<script type="text/javascript" language="JavaScript">';
 1378:     $Str .= 'function toggle_limitby_activity(state) {';
 1379:     $Str .= '    if (state) {';
 1380:     $Str .= '        limitby_startdate_enable();';
 1381:     $Str .= '        limitby_enddate_enable();';
 1382:     $Str .= '    } else {';
 1383:     $Str .= '        limitby_startdate_disable();';
 1384:     $Str .= '        limitby_enddate_disable();';
 1385:     $Str .= '    }';    
 1386:     $Str .= '}';
 1387:     $Str .= '</script>';
 1388:     $Str .= '<fieldset>';
 1389:     my $timecheckbox = '<input type="checkbox" name="limit_by_time" ';
 1390:     if (&limit_by_time()) {
 1391:         $timecheckbox .= ' checked ';
 1392:     } 
 1393:     $timecheckbox .= 'OnChange="javascript:toggle_limitby_activity(this.checked);" ';
 1394:     $timecheckbox .= ' />';
 1395:     $Str .= '<legend><label>'.&mt('[_1] Limit by time',$timecheckbox).'</label></legend>';
 1396:     $Str .= &mt('Start Time: [_1]',$startdateform).'<br />';
 1397:     $Str .= &mt('&nbsp;End Time: [_1]',$enddateform).'<br />';
 1398:     $Str .= '</fieldset>';
 1399:     return $Str;
 1400: }
 1401: 
 1402: sub limit_by_time {
 1403:     if (exists($env{'form.limit_by_time'}) &&
 1404:         $env{'form.limit_by_time'} ne '' ) {
 1405:         return 1;
 1406:     } else {
 1407:         return 0;
 1408:     }
 1409: }
 1410: 
 1411: sub get_time_limits {
 1412:     my $starttime = &Apache::lonhtmlcommon::get_date_from_form
 1413:         ('limitby_startdate');
 1414:     my $endtime = &Apache::lonhtmlcommon::get_date_from_form
 1415:         ('limitby_enddate');
 1416:     return ($starttime,$endtime);
 1417: }
 1418: 
 1419: ####################################################
 1420: ####################################################
 1421: 
 1422: =pod
 1423: 
 1424: =item &manage_caches
 1425: 
 1426: Inputs: $r, apache request object
 1427: 
 1428: Returns: An array of scalars containing html for buttons.
 1429: 
 1430: =cut
 1431: 
 1432: ####################################################
 1433: ####################################################
 1434: sub manage_caches {
 1435:     my ($r,$formname,$inputname,$update_message) = @_;
 1436:     &Apache::loncoursedata::clear_internal_caches();
 1437:     my $sectionkey = 
 1438:         join(',',
 1439:              map {
 1440:                      &escape($_);
 1441:                  } sort(&Apache::lonstatistics::get_selected_sections())
 1442:              );
 1443:     my $statuskey = $Apache::lonstatistics::enrollment_status;
 1444:     if (exists($env{'form.ClearCache'}) || 
 1445:         exists($env{'form.updatecaches'}) || 
 1446:         (exists($env{'form.firstrun'}) && $env{'form.firstrun'} ne 'no') ||
 1447:         (exists($env{'form.prevsection'}) &&
 1448:             $env{'form.prevsection'} ne $sectionkey) ||
 1449:         (exists($env{'form.prevenrollstatus'}) &&
 1450:             $env{'form.prevenrollstatus'} ne $statuskey)
 1451:         ) {
 1452:         if (defined($update_message)) {
 1453:             $r->print($update_message);
 1454:         }
 1455:         if (0) {
 1456:             &Apache::lonnet::logthis('Updating mysql student data caches');
 1457:         }
 1458:         &gather_full_student_data($r,$formname,$inputname);
 1459:     }
 1460:     #
 1461:     my @Buttons = 
 1462:         ('<input type="submit" name="ClearCache" '.
 1463:              'value="'.&mt('Clear Caches').'" />',
 1464:          '<input type="submit" name="updatecaches" '.
 1465:              'value="'.&mt('Update Caches').'" />'.
 1466:          &Apache::loncommon::help_open_topic('Statistics_Cache'),
 1467:          '<input type="hidden" name="prevsection" value="'.$sectionkey.'" />',
 1468:          '<input type="hidden" name="prevenrollstatus" value="'.$statuskey.'" />'
 1469:          );
 1470:     #
 1471:     if (! exists($env{'form.firstrun'})) {
 1472:         $r->print('<input type="hidden" name="firstrun" value="yes" />');
 1473:     } else {
 1474:         $r->print('<input type="hidden" name="firstrun" value="no" />');
 1475:     }
 1476:     #
 1477:     return @Buttons;
 1478: }
 1479: 
 1480: sub gather_full_student_data {
 1481:     my ($r,$formname,$inputname) = @_;
 1482:     my $status_type;
 1483:     if (defined($formname)) {
 1484:         $status_type = 'inline';
 1485:     } else {
 1486:         $status_type = 'popup';
 1487:     }
 1488:     my $c = $r->connection();
 1489:     #
 1490:     &Apache::loncoursedata::clear_internal_caches();
 1491:     #
 1492:     my @Students = @Apache::lonstatistics::Students;
 1493:     #
 1494:     # Open the progress window
 1495:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
 1496:         ($r,&mt('Student Data Compilation Status'),
 1497:          &mt('Student Data Compilation Progress'), scalar(@Students),
 1498:          $status_type,undef,$formname,$inputname);
 1499:     #
 1500:     while (my $student = shift @Students) {
 1501:         return if ($c->aborted());
 1502:         my $status = &Apache::loncoursedata::ensure_current_full_data
 1503:             ($student->{'username'},$student->{'domain'},
 1504:              $env{'request.course.id'});
 1505:         &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 1506:                                                  &mt('last student'));
 1507:     }
 1508:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 1509:     $r->rflush();
 1510:     return;
 1511: }
 1512: 
 1513: ####################################################
 1514: ####################################################
 1515: 
 1516: =pod
 1517: 
 1518: =item &submission_report_form
 1519: 
 1520: Input: The originating reportSelected value for the current stats page.
 1521: 
 1522: Output: Scalar containing HTML with needed form elements and a link to 
 1523: the student submission reports page.
 1524: 
 1525: =cut
 1526: 
 1527: ####################################################
 1528: ####################################################
 1529: sub submission_report_form {
 1530:     my ($original_report) = @_;
 1531:     # Note: In the link below we change the reportSelected value.  If
 1532:     # the user hits the 'back' button on the browser after getting their
 1533:     # student submissions report, this value may still be around.  So we
 1534:     # output a script block to set it properly.  If the $original_report
 1535:     # value is unset, you are just asking for trouble.
 1536:     if (! defined($original_report)) {
 1537:         &Apache::lonnet::logthis
 1538:             ('someone called lonstathelpers::submission_report_form without '.
 1539:              ' enough input.');
 1540:     }
 1541:     my $html = $/.
 1542:         '<script type="text/javascript" language="JavaScript">'.
 1543:         "document.Statistics.reportSelected.value='$original_report';".
 1544:         '</script>'.
 1545:         '<input type="hidden" name="correctans" value="true" />'.
 1546:         '<input type="hidden" name="prob_status" value="true" />'.
 1547:         '<input type="hidden" name="all_sub" value="true" />';
 1548:     my $output_selector = $/.'<select name="output">'.$/;
 1549:     foreach ('HTML','Excel','CSV') {
 1550:         $output_selector .= '    <option value="'.lc($_).'"';
 1551:         if ($env{'form.output'} eq lc($_)) {
 1552:             $output_selector .= ' selected ';
 1553:         }
 1554:         $output_selector .='>'.&mt($_).'</option>'.$/;
 1555:     } 
 1556:     $output_selector .= '</select>'.$/;
 1557:     my $link = '<a href="javascript:'.
 1558:        q{document.Statistics.reportSelected.value='student_submission_reports';}.
 1559:        'document.Statistics.submit();">';
 1560:     $html.= &mt('View data as [_1] [_2]go[_3]',$output_selector,
 1561:                 $link,'</a>').$/;
 1562:     return $html
 1563: }
 1564: 
 1565: ####################################################
 1566: ####################################################
 1567: 
 1568: =pod
 1569: 
 1570: =back
 1571: 
 1572: =cut
 1573: 
 1574: ####################################################
 1575: ####################################################
 1576: 
 1577: 1;
 1578: 
 1579: __END__

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