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

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

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