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

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

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