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

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

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