Annotation of loncom/interface/statistics/lonstathelpers.pm, revision 1.54

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

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