File:  [LON-CAPA] / loncom / interface / loncoursedata.pm
Revision 1.78: download - view: text, annotated - select for diffs
Tue Jun 17 21:45:36 2003 UTC (21 years ago) by matthew
Branches: MAIN
CVS tags: HEAD
Address to some degree the bug we saw today with instructors getting the
white page of death when they view stats or chart.  Now the white page
of death does not appear but the chart and stats think there are no
resources in the course.

    1: # The LearningOnline Network with CAPA
    2: #
    3: # $Id: loncoursedata.pm,v 1.78 2003/06/17 21:45:36 matthew Exp $
    4: #
    5: # Copyright Michigan State University Board of Trustees
    6: #
    7: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    8: #
    9: # LON-CAPA is free software; you can redistribute it and/or modify
   10: # it under the terms of the GNU General Public License as published by
   11: # the Free Software Foundation; either version 2 of the License, or
   12: # (at your option) any later version.
   13: #
   14: # LON-CAPA is distributed in the hope that it will be useful,
   15: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   16: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   17: # GNU General Public License for more details.
   18: #
   19: # You should have received a copy of the GNU General Public License
   20: # along with LON-CAPA; if not, write to the Free Software
   21: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   22: #
   23: # /home/httpd/html/adm/gpl.txt
   24: #
   25: # http://www.lon-capa.org/
   26: #
   27: ###
   28: 
   29: =pod
   30: 
   31: =head1 NAME
   32: 
   33: loncoursedata
   34: 
   35: =head1 SYNOPSIS
   36: 
   37: Set of functions that download and process student and course information.
   38: 
   39: =head1 PACKAGES USED
   40: 
   41:  Apache::Constants qw(:common :http)
   42:  Apache::lonnet()
   43:  Apache::lonhtmlcommon
   44:  HTML::TokeParser
   45:  GDBM_File
   46: 
   47: =cut
   48: 
   49: package Apache::loncoursedata;
   50: 
   51: use strict;
   52: use Apache::Constants qw(:common :http);
   53: use Apache::lonnet();
   54: use Apache::lonhtmlcommon;
   55: use Time::HiRes;
   56: use Apache::lonmysql;
   57: use HTML::TokeParser;
   58: use GDBM_File;
   59: 
   60: =pod
   61: 
   62: =head1 DOWNLOAD INFORMATION
   63: 
   64: This section contains all the functions that get data from other servers 
   65: and/or itself.
   66: 
   67: =cut
   68: 
   69: ####################################################
   70: ####################################################
   71: 
   72: =pod
   73: 
   74: =item &get_sequence_assessment_data()
   75: 
   76: AT THIS TIME THE USE OF THIS FUNCTION IS *NOT* RECOMMENDED
   77: 
   78: Use lonnavmaps to build a data structure describing the order and 
   79: assessment contents of each sequence in the current course.
   80: 
   81: The returned structure is a hash reference. 
   82: 
   83: { title => 'title',
   84:   symb  => 'symb',
   85:   src   => '/s/o/u/r/c/e',
   86:   type  => (container|assessment),
   87:   num_assess   => 2,               # only for container
   88:   parts        => [11,13,15],      # only for assessment
   89:   response_ids => [12,14,16],      # only for assessment
   90:   contents     => [........]       # only for container
   91: }
   92: 
   93: $hash->{'contents'} is a reference to an array of hashes of the same structure.
   94: 
   95: Also returned are array references to the sequences and assessments contained
   96: in the course.
   97: 
   98: 
   99: =cut
  100: 
  101: ####################################################
  102: ####################################################
  103: sub get_sequence_assessment_data {
  104:     my $fn=$ENV{'request.course.fn'};
  105:     ##
  106:     ## use navmaps
  107:     my $navmap = Apache::lonnavmaps::navmap->new($fn.".db",
  108:                                                  $fn."_parms.db",1,0);
  109:     if (!defined($navmap)) {
  110:         return 'Can not open Coursemap';
  111:     }
  112:     # We explicity grab the top level map because I am not sure we
  113:     # are pulling it from the iterator.
  114:     my $top_level_map = $navmap->getById('0.0');
  115:     #
  116:     my $iterator = $navmap->getIterator(undef, undef, undef, 1);
  117:     my $curRes = $iterator->next(); # Top level sequence
  118:     ##
  119:     ## Prime the pump 
  120:     ## 
  121:     ## We are going to loop until we run out of sequences/pages to explore for
  122:     ## resources.  This means we have to start out with something to look
  123:     ## at.
  124:     my $title = $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
  125:     my $symb  = $top_level_map->symb();
  126:     my $src   = $top_level_map->src();
  127:     my $randompick = $top_level_map->randompick();
  128:     #
  129:     my @Sequences; 
  130:     my @Assessments;
  131:     my @Nested_Sequences = ();   # Stack of sequences, keeps track of depth
  132:     my $top = { title    => $title,
  133:                 src      => $src,
  134:                 symb     => $symb,
  135:                 type     => 'container',
  136:                 num_assess => 0,
  137:                 num_assess_parts => 0,
  138:                 contents   => [], 
  139:                 randompick => $randompick,
  140:             };
  141:     push (@Sequences,$top);
  142:     push (@Nested_Sequences, $top);
  143:     #
  144:     # We need to keep track of which sequences contain homework problems
  145:     # 
  146:     my $previous_too;
  147:     my $previous;
  148:     while (scalar(@Nested_Sequences)) {
  149:         $previous_too = $previous;
  150:         $previous = $curRes;
  151:         $curRes = $iterator->next();
  152:         my $currentmap = $Nested_Sequences[-1]; # Last one on the stack
  153:         if ($curRes == $iterator->BEGIN_MAP()) {
  154:             if (! ref($previous)) {
  155:                 $previous = $previous_too;
  156:             }
  157:             if (! ref($previous)) {
  158:                 next;
  159:             }
  160:             # get the map itself, instead of BEGIN_MAP
  161:             $title = $previous->title();
  162:             $symb  = $previous->symb();
  163:             $src   = $previous->src();
  164:             $randompick = $previous->randompick();
  165:             my $newmap = { title    => $title,
  166:                            src      => $src,
  167:                            symb     => $symb,
  168:                            type     => 'container',
  169:                            num_assess => 0,
  170:                            randompick => $randompick,
  171:                            contents   => [],
  172:                        };
  173:             push (@{$currentmap->{'contents'}},$newmap); # this is permanent
  174:             push (@Sequences,$newmap);
  175:             push (@Nested_Sequences, $newmap); # this is a stack
  176:             next;
  177:         }
  178:         if ($curRes == $iterator->END_MAP()) {
  179:             pop(@Nested_Sequences);
  180:             next;
  181:         }
  182:         next if (! ref($curRes));
  183:         next if (! $curRes->is_problem());# && !$curRes->randomout);
  184:         # Okay, from here on out we only deal with assessments
  185:         $title = $curRes->title();
  186:         $symb  = $curRes->symb();
  187:         $src   = $curRes->src();
  188:         my $parts = $curRes->parts();
  189:         my $assessment = { title => $title,
  190:                            src   => $src,
  191:                            symb  => $symb,
  192:                            type  => 'assessment',
  193:                            parts => $parts,
  194:                            num_parts => scalar(@$parts),
  195:                        };
  196:         push(@Assessments,$assessment);
  197:         push(@{$currentmap->{'contents'}},$assessment);
  198:         $currentmap->{'num_assess'}++;
  199:         $currentmap->{'num_assess_parts'}+= scalar(@$parts);
  200:     }
  201:     $navmap->untieHashes();
  202:     return ($top,\@Sequences,\@Assessments);
  203: }
  204: 
  205: sub LoadDiscussion {
  206:     my ($courseID)=@_;
  207:     my %Discuss=();
  208:     my %contrib=&Apache::lonnet::dump(
  209:                 $courseID,
  210:                 $ENV{'course.'.$courseID.'.domain'},
  211:                 $ENV{'course.'.$courseID.'.num'});
  212: 				 
  213:     #my %contrib=&DownloadCourseInformation($name, $courseID, 0);
  214: 
  215:     foreach my $temp(keys %contrib) {
  216: 	if ($temp=~/^version/) {
  217: 	    my $ver=$contrib{$temp};
  218: 	    my ($dummy,$prb)=split(':',$temp);
  219: 	    for (my $idx=1; $idx<=$ver; $idx++ ) {
  220: 		my $name=$contrib{"$idx:$prb:sendername"};
  221: 		$Discuss{"$name:$prb"}=$idx;	
  222: 	    }
  223: 	}
  224:     }       
  225: 
  226:     return \%Discuss;
  227: }
  228: 
  229: ################################################
  230: ################################################
  231: 
  232: =pod
  233: 
  234: =item &GetUserName(username,userdomain)
  235: 
  236: Returns a hash with the following entries:
  237:    'firstname', 'middlename', 'lastname', 'generation', and 'fullname'
  238: 
  239:    'fullname' is the result of &Apache::loncoursedata::ProcessFullName.
  240: 
  241: =cut
  242: 
  243: ################################################
  244: ################################################
  245: sub GetUserName {
  246:     my ($username,$userdomain) = @_;
  247:     $username = $ENV{'user.name'} if (! defined($username));
  248:     $userdomain = $ENV{'user.domain'} if (! defined($username));
  249:     my %userenv = &Apache::lonnet::get('environment',
  250:                            ['firstname','middlename','lastname','generation'],
  251:                                        $userdomain,$username);
  252:     $userenv{'fullname'} = &ProcessFullName($userenv{'lastname'},
  253:                                             $userenv{'generation'},
  254:                                             $userenv{'firstname'},
  255:                                             $userenv{'middlename'});
  256:     return %userenv;
  257: }
  258: 
  259: ################################################
  260: ################################################
  261: 
  262: =pod
  263: 
  264: =item &ProcessFullName()
  265: 
  266: Takes lastname, generation, firstname, and middlename (or some partial
  267: set of this data) and returns the full name version as a string.  Format
  268: is Lastname generation, firstname middlename or a subset of this.
  269: 
  270: =cut
  271: 
  272: ################################################
  273: ################################################
  274: sub ProcessFullName {
  275:     my ($lastname, $generation, $firstname, $middlename)=@_;
  276:     my $Str = '';
  277: 
  278:     # Strip whitespace preceeding & following name components.
  279:     $lastname   =~ s/(\s+$|^\s+)//g;
  280:     $generation =~ s/(\s+$|^\s+)//g;
  281:     $firstname  =~ s/(\s+$|^\s+)//g;
  282:     $middlename =~ s/(\s+$|^\s+)//g;
  283: 
  284:     if($lastname ne '') {
  285: 	$Str .= $lastname;
  286: 	$Str .= ' '.$generation if ($generation ne '');
  287: 	$Str .= ',';
  288:         $Str .= ' '.$firstname  if ($firstname ne '');
  289:         $Str .= ' '.$middlename if ($middlename ne '');
  290:     } else {
  291:         $Str .= $firstname      if ($firstname ne '');
  292:         $Str .= ' '.$middlename if ($middlename ne '');
  293:         $Str .= ' '.$generation if ($generation ne '');
  294:     }
  295: 
  296:     return $Str;
  297: }
  298: 
  299: ################################################
  300: ################################################
  301: 
  302: =pod
  303: 
  304: =item &make_into_hash($values);
  305: 
  306: Returns a reference to a hash as described by $values.  $values is
  307: assumed to be the result of 
  308:     join(':',map {&Apache::lonnet::escape($_)} %orighash);
  309: 
  310: This is a helper function for get_current_state.
  311: 
  312: =cut
  313: 
  314: ################################################
  315: ################################################
  316: sub make_into_hash {
  317:     my $values = shift;
  318:     my %tmp = map { &Apache::lonnet::unescape($_); }
  319:                                            split(':',$values);
  320:     return \%tmp;
  321: }
  322: 
  323: 
  324: ################################################
  325: ################################################
  326: 
  327: =pod
  328: 
  329: =head1 LOCAL DATA CACHING SUBROUTINES
  330: 
  331: The local caching is done using MySQL.  There is no fall-back implementation
  332: if MySQL is not running.
  333: 
  334: The programmers interface is to call &get_current_state() or some other
  335: primary interface subroutine (described below).  The internals of this 
  336: storage system are documented here.
  337: 
  338: There are six tables used to store student performance data (the results of
  339: a dumpcurrent).  Each of these tables is created in MySQL with a name of
  340: $courseid_*****, where ***** is 'symb', 'part', or whatever is appropriate 
  341: for the table.  The tables and their purposes are described below.
  342: 
  343: Some notes before we get started.
  344: 
  345: Each table must have a PRIMARY KEY, which is a column or set of columns which
  346: will serve to uniquely identify a row of data.  NULL is not allowed!
  347: 
  348: INDEXes work best on integer data.
  349: 
  350: JOIN is used to combine data from many tables into one output.
  351: 
  352: lonmysql.pm is used for some of the interface, specifically the table creation
  353: calls.  The inserts are done in bulk by directly calling the database handler.
  354: The SELECT ... JOIN statement used to retrieve the data does not have an
  355: interface in lonmysql.pm and I shudder at the thought of writing one.
  356: 
  357: =head3 Table Descriptions
  358: 
  359: =over 4
  360: 
  361: =item $symb_table
  362: 
  363: The symb_table has two columns.  The first is a 'symb_id' and the second
  364: is the text name for the 'symb' (limited to 64k).  The 'symb_id' is generated
  365: automatically by MySQL so inserts should be done on this table with an
  366: empty first element.  This table has its PRIMARY KEY on the 'symb_id'.
  367: 
  368: =item $part_table
  369: 
  370: The part_table has two columns.  The first is a 'part_id' and the second
  371: is the text name for the 'part' (limited to 100 characters).  The 'part_id' is
  372: generated automatically by MySQL so inserts should be done on this table with
  373: an empty first element.  This table has its PRIMARY KEY on the 'part' (100
  374: characters) and a KEY on 'part_id'.
  375: 
  376: =item $student_table
  377: 
  378: The student_table has two columns.  The first is a 'student_id' and the second
  379: is the text description of the 'student' (typically username:domain) (less
  380: than 100 characters).  The 'student_id' is automatically generated by MySQL.
  381: The use of the name 'student_id' is loaded, I know, but this ID is used ONLY 
  382: internally to the MySQL database and is not the same as the students ID 
  383: (stored in the students environment).  This table has its PRIMARY KEY on the
  384: 'student' (100 characters).
  385: 
  386: =item $updatetime_table
  387: 
  388: The updatetime_table has two columns.  The first is 'student' (100 characters,
  389: typically username:domain).  The second is 'updatetime', which is an unsigned
  390: integer, NOT a MySQL date.  This table has its PRIMARY KEY on 'student' (100
  391: characters).
  392: 
  393: =item $performance_table
  394: 
  395: The performance_table has 9 columns.  The first three are 'symb_id', 
  396: 'student_id', and 'part_id'.  These comprise the PRIMARY KEY for this table
  397: and are directly related to the $symb_table, $student_table, and $part_table
  398: described above.  MySQL does better indexing on numeric items than text,
  399: so we use these three "index tables".  The remaining columns are
  400: 'solved', 'tries', 'awarded', 'award', 'awarddetail', and 'timestamp'.
  401: These are either the MySQL type TINYTEXT or various integers ('tries' and 
  402: 'timestamp').  This table has KEYs of 'student_id' and 'symb_id'.
  403: For use of this table, see the functions described below.
  404: 
  405: =item $parameters_table
  406: 
  407: The parameters_table holds the data that does not fit neatly into the
  408: performance_table.  The parameters table has four columns: 'symb_id',
  409: 'student_id', 'parameter', and 'value'.  'symb_id', 'student_id', and
  410: 'parameter' comprise the PRIMARY KEY for this table.  'parameter' is 
  411: limited to 255 characters.  'value' is limited to 64k characters.
  412: 
  413: =back
  414: 
  415: =head3 Important Subroutines
  416: 
  417: Here is a brief overview of the subroutines which are likely to be of 
  418: interest:
  419: 
  420: =over 4
  421: 
  422: =item &get_current_state(): programmers interface.
  423: 
  424: =item &init_dbs(): table creation
  425: 
  426: =item &update_student_data(): data storage calls
  427: 
  428: =item &get_student_data_from_performance_cache(): data retrieval
  429: 
  430: =back
  431: 
  432: =head3 Main Documentation
  433: 
  434: =over 4
  435: 
  436: =cut
  437: 
  438: ################################################
  439: ################################################
  440: 
  441: ################################################
  442: ################################################
  443: {
  444: 
  445: my $current_course ='';
  446: my $symb_table;
  447: my $part_table;
  448: my $student_table;
  449: my $updatetime_table;
  450: my $performance_table;
  451: my $parameters_table;
  452: 
  453: ################################################
  454: ################################################
  455: 
  456: =pod
  457: 
  458: =item &init_dbs()
  459: 
  460: Input: course id
  461: 
  462: Output: 0 on success, positive integer on error
  463: 
  464: This routine issues the calls to lonmysql to create the tables used to
  465: store student data.
  466: 
  467: =cut
  468: 
  469: ################################################
  470: ################################################
  471: sub init_dbs {
  472:     my $courseid = shift;
  473:     &setup_table_names($courseid);
  474:     #
  475:     # Drop any of the existing tables
  476:     foreach my $table ($symb_table,$part_table,$student_table,
  477:                        $updatetime_table,$performance_table,
  478:                        $parameters_table) {
  479:         &Apache::lonmysql::drop_table($table);
  480:     }
  481:     #
  482:     # Note - changes to this table must be reflected in the code that 
  483:     # stores the data (calls &Apache::lonmysql::store_row with this table
  484:     # id
  485:     my $symb_table_def = {
  486:         id => $symb_table,
  487:         permanent => 'no',
  488:         columns => [{ name => 'symb_id',
  489:                       type => 'MEDIUMINT UNSIGNED',
  490:                       restrictions => 'NOT NULL',
  491:                       auto_inc     => 'yes', },
  492:                     { name => 'symb',
  493:                       type => 'MEDIUMTEXT',
  494:                       restrictions => 'NOT NULL'},
  495:                     ],
  496:         'PRIMARY KEY' => ['symb_id'],
  497:     };
  498:     #
  499:     my $part_table_def = {
  500:         id => $part_table,
  501:         permanent => 'no',
  502:         columns => [{ name => 'part_id',
  503:                       type => 'MEDIUMINT UNSIGNED',
  504:                       restrictions => 'NOT NULL',
  505:                       auto_inc     => 'yes', },
  506:                     { name => 'part',
  507:                       type => 'VARCHAR(100)',
  508:                       restrictions => 'NOT NULL'},
  509:                     ],
  510:         'PRIMARY KEY' => ['part (100)'],
  511:         'KEY' => [{ columns => ['part_id']},],
  512:     };
  513:     #
  514:     my $student_table_def = {
  515:         id => $student_table,
  516:         permanent => 'no',
  517:         columns => [{ name => 'student_id',
  518:                       type => 'MEDIUMINT UNSIGNED',
  519:                       restrictions => 'NOT NULL',
  520:                       auto_inc     => 'yes', },
  521:                     { name => 'student',
  522:                       type => 'VARCHAR(100)',
  523:                       restrictions => 'NOT NULL'},
  524:                     ],
  525:         'PRIMARY KEY' => ['student (100)'],
  526:         'KEY' => [{ columns => ['student_id']},],
  527:     };
  528:     #
  529:     my $updatetime_table_def = {
  530:         id => $updatetime_table,
  531:         permanent => 'no',
  532:         columns => [{ name => 'student',
  533:                       type => 'VARCHAR(100)',
  534:                       restrictions => 'NOT NULL UNIQUE',},
  535:                     { name => 'updatetime',
  536:                       type => 'INT UNSIGNED',
  537:                       restrictions => 'NOT NULL' },
  538:                     ],
  539:         'PRIMARY KEY' => ['student (100)'],
  540:     };
  541:     #
  542:     my $performance_table_def = {
  543:         id => $performance_table,
  544:         permanent => 'no',
  545:         columns => [{ name => 'symb_id',
  546:                       type => 'MEDIUMINT UNSIGNED',
  547:                       restrictions => 'NOT NULL'  },
  548:                     { name => 'student_id',
  549:                       type => 'MEDIUMINT UNSIGNED',
  550:                       restrictions => 'NOT NULL'  },
  551:                     { name => 'part_id',
  552:                       type => 'MEDIUMINT UNSIGNED',
  553:                       restrictions => 'NOT NULL' },
  554:                     { name => 'part',
  555:                       type => 'VARCHAR(100)',
  556:                       restrictions => 'NOT NULL'},                    
  557:                     { name => 'solved',
  558:                       type => 'TINYTEXT' },
  559:                     { name => 'tries',
  560:                       type => 'SMALLINT UNSIGNED' },
  561:                     { name => 'awarded',
  562:                       type => 'TINYTEXT' },
  563:                     { name => 'award',
  564:                       type => 'TINYTEXT' },
  565:                     { name => 'awarddetail',
  566:                       type => 'TINYTEXT' },
  567:                     { name => 'timestamp',
  568:                       type => 'INT UNSIGNED'},
  569:                     ],
  570:         'PRIMARY KEY' => ['symb_id','student_id','part_id'],
  571:         'KEY' => [{ columns=>['student_id'] },
  572:                   { columns=>['symb_id'] },],
  573:     };
  574:     #
  575:     my $parameters_table_def = {
  576:         id => $parameters_table,
  577:         permanent => 'no',
  578:         columns => [{ name => 'symb_id',
  579:                       type => 'MEDIUMINT UNSIGNED',
  580:                       restrictions => 'NOT NULL'  },
  581:                     { name => 'student_id',
  582:                       type => 'MEDIUMINT UNSIGNED',
  583:                       restrictions => 'NOT NULL'  },
  584:                     { name => 'parameter',
  585:                       type => 'TINYTEXT',
  586:                       restrictions => 'NOT NULL'  },
  587:                     { name => 'value',
  588:                       type => 'MEDIUMTEXT' },
  589:                     ],
  590:         'PRIMARY KEY' => ['symb_id','student_id','parameter (255)'],
  591:     };
  592:     #
  593:     # Create the tables
  594:     my $tableid;
  595:     $tableid = &Apache::lonmysql::create_table($symb_table_def);
  596:     if (! defined($tableid)) {
  597:         &Apache::lonnet::logthis("error creating symb_table: ".
  598:                                  &Apache::lonmysql::get_error());
  599:         return 1;
  600:     }
  601:     #
  602:     $tableid = &Apache::lonmysql::create_table($part_table_def);
  603:     if (! defined($tableid)) {
  604:         &Apache::lonnet::logthis("error creating part_table: ".
  605:                                  &Apache::lonmysql::get_error());
  606:         return 2;
  607:     }
  608:     #
  609:     $tableid = &Apache::lonmysql::create_table($student_table_def);
  610:     if (! defined($tableid)) {
  611:         &Apache::lonnet::logthis("error creating student_table: ".
  612:                                  &Apache::lonmysql::get_error());
  613:         return 3;
  614:     }
  615:     #
  616:     $tableid = &Apache::lonmysql::create_table($updatetime_table_def);
  617:     if (! defined($tableid)) {
  618:         &Apache::lonnet::logthis("error creating updatetime_table: ".
  619:                                  &Apache::lonmysql::get_error());
  620:         return 4;
  621:     }
  622:     #
  623:     $tableid = &Apache::lonmysql::create_table($performance_table_def);
  624:     if (! defined($tableid)) {
  625:         &Apache::lonnet::logthis("error creating preformance_table: ".
  626:                                  &Apache::lonmysql::get_error());
  627:         return 5;
  628:     }
  629:     #
  630:     $tableid = &Apache::lonmysql::create_table($parameters_table_def);
  631:     if (! defined($tableid)) {
  632:         &Apache::lonnet::logthis("error creating parameters_table: ".
  633:                                  &Apache::lonmysql::get_error());
  634:         return 6;
  635:     }
  636:     return 0;
  637: }
  638: 
  639: ################################################
  640: ################################################
  641: 
  642: =pod
  643: 
  644: =item &delete_caches()
  645: 
  646: =cut
  647: 
  648: ################################################
  649: ################################################
  650: sub delete_caches {
  651:     my $courseid = shift;
  652:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
  653:     #
  654:     &setup_table_names($courseid);
  655:     #
  656:     my $dbh = &Apache::lonmysql::get_dbh();
  657:     foreach my $table ($symb_table,$part_table,$student_table,
  658:                        $updatetime_table,$performance_table,
  659:                        $parameters_table ){
  660:         my $command = 'DROP TABLE '.$table.';';
  661:         $dbh->do($command);
  662:         if ($dbh->err) {
  663:             &Apache::lonnet::logthis($command.' resulted in error: '.$dbh->errstr);
  664:         }
  665:     }
  666:     return;
  667: }
  668: 
  669: ################################################
  670: ################################################
  671: 
  672: =pod
  673: 
  674: =item &get_part_id()
  675: 
  676: Get the MySQL id of a problem part string.
  677: 
  678: Input: $part
  679: 
  680: Output: undef on error, integer $part_id on success.
  681: 
  682: =item &get_part()
  683: 
  684: Get the string describing a part from the MySQL id of the problem part.
  685: 
  686: Input: $part_id
  687: 
  688: Output: undef on error, $part string on success.
  689: 
  690: =cut
  691: 
  692: ################################################
  693: ################################################
  694: 
  695: my $have_read_part_table = 0;
  696: my %ids_by_part;
  697: my %parts_by_id;
  698: 
  699: sub get_part_id {
  700:     my ($part) = @_;
  701:     $part = 0 if (! defined($part));
  702:     if (! $have_read_part_table) {
  703:         my @Result = &Apache::lonmysql::get_rows($part_table);
  704:         foreach (@Result) {
  705:             $ids_by_part{$_->[1]}=$_->[0];
  706:         }
  707:         $have_read_part_table = 1;
  708:     }
  709:     if (! exists($ids_by_part{$part})) {
  710:         &Apache::lonmysql::store_row($part_table,[undef,$part]);
  711:         undef(%ids_by_part);
  712:         my @Result = &Apache::lonmysql::get_rows($part_table);
  713:         foreach (@Result) {
  714:             $ids_by_part{$_->[1]}=$_->[0];
  715:         }
  716:     }
  717:     return $ids_by_part{$part} if (exists($ids_by_part{$part}));
  718:     return undef; # error
  719: }
  720: 
  721: sub get_part {
  722:     my ($part_id) = @_;
  723:     if (! exists($parts_by_id{$part_id})  || 
  724:         ! defined($parts_by_id{$part_id}) ||
  725:         $parts_by_id{$part_id} eq '') {
  726:         my @Result = &Apache::lonmysql::get_rows($part_table);
  727:         foreach (@Result) {
  728:             $parts_by_id{$_->[0]}=$_->[1];
  729:         }
  730:     }
  731:     return $parts_by_id{$part_id} if(exists($parts_by_id{$part_id}));
  732:     return undef; # error
  733: }
  734: 
  735: ################################################
  736: ################################################
  737: 
  738: =pod
  739: 
  740: =item &get_symb_id()
  741: 
  742: Get the MySQL id of a symb.
  743: 
  744: Input: $symb
  745: 
  746: Output: undef on error, integer $symb_id on success.
  747: 
  748: =item &get_symb()
  749: 
  750: Get the symb associated with a MySQL symb_id.
  751: 
  752: Input: $symb_id
  753: 
  754: Output: undef on error, $symb on success.
  755: 
  756: =cut
  757: 
  758: ################################################
  759: ################################################
  760: 
  761: my $have_read_symb_table = 0;
  762: my %ids_by_symb;
  763: my %symbs_by_id;
  764: 
  765: sub get_symb_id {
  766:     my ($symb) = @_;
  767:     if (! $have_read_symb_table) {
  768:         my @Result = &Apache::lonmysql::get_rows($symb_table);
  769:         foreach (@Result) {
  770:             $ids_by_symb{$_->[1]}=$_->[0];
  771:         }
  772:         $have_read_symb_table = 1;
  773:     }
  774:     if (! exists($ids_by_symb{$symb})) {
  775:         &Apache::lonmysql::store_row($symb_table,[undef,$symb]);
  776:         undef(%ids_by_symb);
  777:         my @Result = &Apache::lonmysql::get_rows($symb_table);
  778:         foreach (@Result) {
  779:             $ids_by_symb{$_->[1]}=$_->[0];
  780:         }
  781:     }
  782:     return $ids_by_symb{$symb} if(exists( $ids_by_symb{$symb}));
  783:     return undef; # error
  784: }
  785: 
  786: sub get_symb {
  787:     my ($symb_id) = @_;
  788:     if (! exists($symbs_by_id{$symb_id})  || 
  789:         ! defined($symbs_by_id{$symb_id}) ||
  790:         $symbs_by_id{$symb_id} eq '') {
  791:         my @Result = &Apache::lonmysql::get_rows($symb_table);
  792:         foreach (@Result) {
  793:             $symbs_by_id{$_->[0]}=$_->[1];
  794:         }
  795:     }
  796:     return $symbs_by_id{$symb_id} if(exists( $symbs_by_id{$symb_id}));
  797:     return undef; # error
  798: }
  799: 
  800: ################################################
  801: ################################################
  802: 
  803: =pod
  804: 
  805: =item &get_student_id()
  806: 
  807: Get the MySQL id of a student.
  808: 
  809: Input: $sname, $dom
  810: 
  811: Output: undef on error, integer $student_id on success.
  812: 
  813: =item &get_student()
  814: 
  815: Get student username:domain associated with the MySQL student_id.
  816: 
  817: Input: $student_id
  818: 
  819: Output: undef on error, string $student (username:domain) on success.
  820: 
  821: =cut
  822: 
  823: ################################################
  824: ################################################
  825: 
  826: my $have_read_student_table = 0;
  827: my %ids_by_student;
  828: my %students_by_id;
  829: 
  830: sub get_student_id {
  831:     my ($sname,$sdom) = @_;
  832:     my $student = $sname.':'.$sdom;
  833:     if (! $have_read_student_table) {
  834:         my @Result = &Apache::lonmysql::get_rows($student_table);
  835:         foreach (@Result) {
  836:             $ids_by_student{$_->[1]}=$_->[0];
  837:         }
  838:         $have_read_student_table = 1;
  839:     }
  840:     if (! exists($ids_by_student{$student})) {
  841:         &Apache::lonmysql::store_row($student_table,[undef,$student]);
  842:         undef(%ids_by_student);
  843:         my @Result = &Apache::lonmysql::get_rows($student_table);
  844:         foreach (@Result) {
  845:             $ids_by_student{$_->[1]}=$_->[0];
  846:         }
  847:     }
  848:     return $ids_by_student{$student} if(exists( $ids_by_student{$student}));
  849:     return undef; # error
  850: }
  851: 
  852: sub get_student {
  853:     my ($student_id) = @_;
  854:     if (! exists($students_by_id{$student_id})  || 
  855:         ! defined($students_by_id{$student_id}) ||
  856:         $students_by_id{$student_id} eq '') {
  857:         my @Result = &Apache::lonmysql::get_rows($student_table);
  858:         foreach (@Result) {
  859:             $students_by_id{$_->[0]}=$_->[1];
  860:         }
  861:     }
  862:     return $students_by_id{$student_id} if(exists($students_by_id{$student_id}));
  863:     return undef; # error
  864: }
  865: 
  866: ################################################
  867: ################################################
  868: 
  869: =pod
  870: 
  871: =item &update_student_data()
  872: 
  873: Input: $sname, $sdom, $courseid
  874: 
  875: Output: $returnstatus, \%student_data
  876: 
  877: $returnstatus is a string describing any errors that occured.  'okay' is the
  878: default.
  879: \%student_data is the data returned by a call to lonnet::currentdump.
  880: 
  881: This subroutine loads a students data using lonnet::currentdump and inserts
  882: it into the MySQL database.  The inserts are done on two tables, 
  883: $performance_table and $parameters_table.  $parameters_table holds the data 
  884: that is not included in $performance_table.  See the description of 
  885: $performance_table elsewhere in this file.  The INSERT calls are made
  886: directly by this subroutine, not through lonmysql because we do a 'bulk'
  887: insert which takes advantage of MySQLs non-SQL compliant INSERT command to 
  888: insert multiple rows at a time.  If anything has gone wrong during this
  889: process, $returnstatus is updated with a description of the error and
  890: \%student_data is returned.  
  891: 
  892: Notice we do not insert the data and immediately query it.  This means it
  893: is possible for there to be data returned this first time that is not 
  894: available the second time.  CYA.
  895: 
  896: =cut
  897: 
  898: ################################################
  899: ################################################
  900: sub update_student_data {
  901:     my ($sname,$sdom,$courseid) = @_;
  902:     #
  903:     # Set up database names
  904:     &setup_table_names($courseid);
  905:     #
  906:     my $student_id = &get_student_id($sname,$sdom);
  907:     my $student = $sname.':'.$sdom;
  908:     #
  909:     my $returnstatus = 'okay';
  910:     #
  911:     # Download students data
  912:     my $time_of_retrieval = time;
  913:     my @tmp = &Apache::lonnet::currentdump($courseid,$sdom,$sname);
  914:     if ((scalar(@tmp) > 0) && ($tmp[0] =~ /^error:/)) {
  915:         &Apache::lonnet::logthis('error getting data for '.
  916:                                  $sname.':'.$sdom.' in course '.$courseid.
  917:                                  ':'.$tmp[0]);
  918:         $returnstatus = 'error getting data';
  919:         return $returnstatus;
  920:     }
  921:     if (scalar(@tmp) < 1) {
  922:         return ('no data',undef);
  923:     }
  924:     my %student_data = @tmp;
  925:     #
  926:     # Remove all of the students data from the table
  927:     my $dbh = &Apache::lonmysql::get_dbh();
  928:     $dbh->do('DELETE FROM '.$performance_table.' WHERE student_id='.
  929:              $student_id);
  930:     $dbh->do('DELETE FROM '.$parameters_table.' WHERE student_id='.
  931:              $student_id);
  932:     #
  933:     # Store away the data
  934:     #
  935:     my $starttime = Time::HiRes::time;
  936:     my $elapsed = 0;
  937:     my $rows_stored;
  938:     my $store_parameters_command  = 'INSERT INTO '.$parameters_table.
  939:         ' VALUES '."\n";
  940:     my $num_parameters = 0;
  941:     my $store_performance_command = 'INSERT INTO '.$performance_table.
  942:         ' VALUES '."\n";
  943:     return 'error' if (! defined($dbh));
  944:     while (my ($current_symb,$param_hash) = each(%student_data)) {
  945:         #
  946:         # make sure the symb is set up properly
  947:         my $symb_id = &get_symb_id($current_symb);
  948:         #
  949:         # Load data into the tables
  950:         while (my ($parameter,$value) = each(%$param_hash)) {
  951:             my $newstring;
  952:             if ($parameter !~ /(timestamp|resource\.(.*)\.(solved|tries|awarded|award|awarddetail|previous))/) {
  953:                 $newstring = "('".join("','",
  954:                                        $symb_id,$student_id,
  955:                                        $parameter)."',".
  956:                                            $dbh->quote($value)."),\n";
  957:                 $num_parameters ++;
  958:                 if ($newstring !~ /''/) {
  959:                     $store_parameters_command .= $newstring;
  960:                     $rows_stored++;
  961:                 }
  962:             }
  963:             next if ($parameter !~ /^resource\.(.*)\.solved$/);
  964:             #
  965:             my $part = $1;
  966:             my $part_id = &get_part_id($part);
  967:             next if (!defined($part_id));
  968:             my $solved  = $value;
  969:             my $tries   = $param_hash->{'resource.'.$part.'.tries'};
  970:             my $awarded = $param_hash->{'resource.'.$part.'.awarded'};
  971:             my $award   = $param_hash->{'resource.'.$part.'.award'};
  972:             my $awarddetail = $param_hash->{'resource.'.$part.'.awarddetail'};
  973:             my $timestamp = $param_hash->{'timestamp'};
  974:             #
  975:             $solved      = '' if (! defined($solved));
  976:             $tries       = '' if (! defined($tries));
  977:             $awarded     = '' if (! defined($awarded));
  978:             $award       = '' if (! defined($award));
  979:             $awarddetail = '' if (! defined($awarddetail));
  980:             $newstring = "('".join("','",$symb_id,$student_id,$part_id,$part,
  981:                                    $solved,$tries,$awarded,$award,
  982:                                    $awarddetail,$timestamp)."'),\n";
  983:             $store_performance_command .= $newstring;
  984:             $rows_stored++;
  985:         }
  986:     }
  987:     chop $store_parameters_command;
  988:     chop $store_parameters_command;
  989:     chop $store_performance_command;
  990:     chop $store_performance_command;
  991:     my $start = Time::HiRes::time;
  992:     $dbh->do($store_parameters_command) if ($num_parameters>0);
  993:     if ($dbh->err()) {
  994:         &Apache::lonnet::logthis(' bigass insert error:'.$dbh->errstr());
  995:         &Apache::lonnet::logthis('command = '.$store_parameters_command);
  996:         $returnstatus = 'error: unable to insert parameters into database';
  997:         return $returnstatus,\%student_data;
  998:     }
  999:     $dbh->do($store_performance_command);
 1000:     if ($dbh->err()) {
 1001:         &Apache::lonnet::logthis(' bigass insert error:'.$dbh->errstr());
 1002:         &Apache::lonnet::logthis('command = '.$store_performance_command);
 1003:         $returnstatus = 'error: unable to insert performance into database';
 1004:         return $returnstatus,\%student_data;
 1005:     }
 1006:     $elapsed += Time::HiRes::time - $start;
 1007:     #
 1008:     # Set the students update time
 1009:     &Apache::lonmysql::replace_row($updatetime_table,
 1010:                                    [$student,$time_of_retrieval]);
 1011:     return ($returnstatus,\%student_data);
 1012: }
 1013: 
 1014: ################################################
 1015: ################################################
 1016: 
 1017: =pod
 1018: 
 1019: =item &ensure_current_data()
 1020: 
 1021: Input: $sname, $sdom, $courseid
 1022: 
 1023: Output: $status, $data
 1024: 
 1025: This routine ensures the data for a given student is up to date.  It calls
 1026: &init_dbs() if the tables do not exist.  The $updatetime_table is queried
 1027: to determine the time of the last update.  If the students data is out of
 1028: date, &update_student_data() is called.  The return values from the call
 1029: to &update_student_data() are returned.
 1030: 
 1031: =cut
 1032: 
 1033: ################################################
 1034: ################################################
 1035: sub ensure_current_data {
 1036:     my ($sname,$sdom,$courseid) = @_;
 1037:     my $status = 'okay';   # return value
 1038:     #
 1039:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
 1040:     # 
 1041:     # Clean out package variables
 1042:     &setup_table_names($courseid);
 1043:     #
 1044:     # if the tables do not exist, make them
 1045:     my @CurrentTable = &Apache::lonmysql::tables_in_db();
 1046:     my ($found_symb,$found_student,$found_part,$found_update,
 1047:         $found_performance,$found_parameters);
 1048:     foreach (@CurrentTable) {
 1049:         $found_symb        = 1 if ($_ eq $symb_table);
 1050:         $found_student     = 1 if ($_ eq $student_table);
 1051:         $found_part        = 1 if ($_ eq $part_table);
 1052:         $found_update      = 1 if ($_ eq $updatetime_table);
 1053:         $found_performance = 1 if ($_ eq $performance_table);
 1054:         $found_parameters  = 1 if ($_ eq $parameters_table);
 1055:     }
 1056:     if (!$found_symb        || !$found_update || 
 1057:         !$found_student     || !$found_part   ||
 1058:         !$found_performance || !$found_parameters) {
 1059:         if (&init_dbs($courseid)) {
 1060:             return 'error';
 1061:         }
 1062:     }
 1063:     #
 1064:     # Get the update time for the user
 1065:     my $updatetime = 0;
 1066:     my $modifiedtime = &Apache::lonnet::GetFileTimestamp
 1067:         ($sdom,$sname,$courseid.'.db',
 1068:          $Apache::lonnet::perlvar{'lonUsersDir'});
 1069:     #
 1070:     my $student = $sname.':'.$sdom;
 1071:     my @Result = &Apache::lonmysql::get_rows($updatetime_table,
 1072:                                              "student ='$student'");
 1073:     my $data = undef;
 1074:     if (@Result) {
 1075:         $updatetime = $Result[0]->[1];
 1076:     }
 1077:     if ($modifiedtime > $updatetime) {
 1078:         ($status,$data) = &update_student_data($sname,$sdom,$courseid);
 1079:     }
 1080:     return ($status,$data);
 1081: }
 1082: 
 1083: ################################################
 1084: ################################################
 1085: 
 1086: =pod
 1087: 
 1088: =item &get_student_data_from_performance_cache()
 1089: 
 1090: Input: $sname, $sdom, $symb, $courseid
 1091: 
 1092: Output: hash reference containing the data for the given student.
 1093: If $symb is undef, all the students data is returned.
 1094: 
 1095: This routine is the heart of the local caching system.  See the description
 1096: of $performance_table, $symb_table, $student_table, and $part_table.  The
 1097: main task is building the MySQL request.  The tables appear in the request
 1098: in the order in which they should be parsed by MySQL.  When searching
 1099: on a student the $student_table is used to locate the 'student_id'.  All
 1100: rows in $performance_table which have a matching 'student_id' are returned,
 1101: with data from $part_table and $symb_table which match the entries in
 1102: $performance_table, 'part_id' and 'symb_id'.  When searching on a symb,
 1103: the $symb_table is processed first, with matching rows grabbed from 
 1104: $performance_table and filled in from $part_table and $student_table in
 1105: that order.  
 1106: 
 1107: Running 'EXPLAIN ' on the 'SELECT' statements generated can be quite 
 1108: interesting, especially if you play with the order the tables are listed.  
 1109: 
 1110: =cut
 1111: 
 1112: ################################################
 1113: ################################################
 1114: sub get_student_data_from_performance_cache {
 1115:     my ($sname,$sdom,$symb,$courseid)=@_;
 1116:     my $student = $sname.':'.$sdom if (defined($sname) && defined($sdom));
 1117:     &setup_table_names($courseid);
 1118:     #
 1119:     # Return hash
 1120:     my $studentdata;
 1121:     #
 1122:     my $dbh = &Apache::lonmysql::get_dbh();
 1123:     my $request = "SELECT ".
 1124:         "d.symb,a.part,a.solved,a.tries,a.awarded,a.award,a.awarddetail,".
 1125:             "a.timestamp ";
 1126:     if (defined($student)) {
 1127:         $request .= "FROM $student_table AS b ".
 1128:             "LEFT JOIN $performance_table AS a ON b.student_id=a.student_id ".
 1129: #            "LEFT JOIN $part_table AS c ON c.part_id = a.part_id ".
 1130:             "LEFT JOIN $symb_table AS d ON d.symb_id = a.symb_id ".
 1131:                 "WHERE student='$student'";
 1132:         if (defined($symb) && $symb ne '') {
 1133:             $request .= " AND d.symb=".$dbh->quote($symb);
 1134:         }
 1135:     } elsif (defined($symb) && $symb ne '') {
 1136:         $request .= "FROM $symb_table as d ".
 1137:             "LEFT JOIN $performance_table AS a ON d.symb_id=a.symb_id ".
 1138: #            "LEFT JOIN $part_table    AS c ON c.part_id = a.part_id ".
 1139:             "LEFT JOIN $student_table AS b ON b.student_id = a.student_id ".
 1140:                 "WHERE symb='".$dbh->quote($symb)."'";
 1141:     }
 1142:     my $starttime = Time::HiRes::time;
 1143:     my $rows_retrieved = 0;
 1144:     my $sth = $dbh->prepare($request);
 1145:     $sth->execute();
 1146:     if ($sth->err()) {
 1147:         &Apache::lonnet::logthis("Unable to execute MySQL request:");
 1148:         &Apache::lonnet::logthis("\n".$request."\n");
 1149:         &Apache::lonnet::logthis("error is:".$sth->errstr());
 1150:         return undef;
 1151:     }
 1152:     foreach my $row (@{$sth->fetchall_arrayref}) {
 1153:         $rows_retrieved++;
 1154:         my ($symb,$part,$solved,$tries,$awarded,$award,$awarddetail,$time) = 
 1155:             (@$row);
 1156:         my $base = 'resource.'.$part;
 1157:         $studentdata->{$symb}->{$base.'.solved'}  = $solved;
 1158:         $studentdata->{$symb}->{$base.'.tries'}   = $tries;
 1159:         $studentdata->{$symb}->{$base.'.awarded'} = $awarded;
 1160:         $studentdata->{$symb}->{$base.'.award'}   = $award;
 1161:         $studentdata->{$symb}->{$base.'.awarddetail'} = $awarddetail;
 1162:         $studentdata->{$symb}->{'timestamp'} = $time if (defined($time) && $time ne '');
 1163:     }
 1164:     if (defined($symb) && $symb ne '') {
 1165:         $studentdata = $studentdata->{$symb};
 1166:     }
 1167:     return $studentdata;
 1168: }
 1169: 
 1170: ################################################
 1171: ################################################
 1172: 
 1173: =pod
 1174: 
 1175: =item &get_current_state()
 1176: 
 1177: Input: $sname,$sdom,$symb,$courseid
 1178: 
 1179: Output: Described below
 1180: 
 1181: Retrieve the current status of a students performance.  $sname and
 1182: $sdom are the only required parameters.  If $symb is undef the results
 1183: of an &Apache::lonnet::currentdump() will be returned.  
 1184: If $courseid is undef it will be retrieved from the environment.
 1185: 
 1186: The return structure is based on &Apache::lonnet::currentdump.  If
 1187: $symb is unspecified, all the students data is returned in a hash of
 1188: the form:
 1189: ( 
 1190:   symb1 => { param1 => value1, param2 => value2 ... },
 1191:   symb2 => { param1 => value1, param2 => value2 ... },
 1192: )
 1193: 
 1194: If $symb is specified, a hash of 
 1195: (
 1196:   param1 => value1, 
 1197:   param2 => value2,
 1198: )
 1199: is returned.
 1200: 
 1201: If no data is found for $symb, or if the student has no performance data,
 1202: an empty list is returned.
 1203: 
 1204: =cut
 1205: 
 1206: ################################################
 1207: ################################################
 1208: sub get_current_state {
 1209:     my ($sname,$sdom,$symb,$courseid,$forcedownload)=@_;
 1210:     #
 1211:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
 1212:     #
 1213:     return () if (! defined($sname) || ! defined($sdom));
 1214:     #
 1215:     my ($status,$data) = &ensure_current_data($sname,$sdom,$courseid);
 1216: #    &Apache::lonnet::logthis
 1217: #        ('sname = '.$sname.
 1218: #         ' domain = '.$sdom.
 1219: #         ' status = '.$status.
 1220: #         ' data is '.(defined($data)?'defined':'undefined'));
 1221: #    while (my ($symb,$hash) = each(%$data)) {
 1222: #        &Apache::lonnet::logthis($symb."\n----------------------------------");
 1223: #        while (my ($key,$value) = each (%$hash)) {
 1224: #            &Apache::lonnet::logthis("   ".$key." = ".$value);
 1225: #        }
 1226: #    }
 1227:     #
 1228:     if (defined($data)) {
 1229:         if (defined($symb)) {
 1230:             return %{$data->{$symb}};
 1231:         } else {
 1232:             return %$data;
 1233:         }
 1234:     } elsif ($status eq 'no data') {
 1235:         return ();
 1236:     } else {
 1237:         if ($status ne 'okay' && $status ne '') {
 1238:             &Apache::lonnet::logthis('status = '.$status);
 1239:             return ();
 1240:         }
 1241:         my $returnhash = &get_student_data_from_performance_cache($sname,$sdom,
 1242:                                                       $symb,$courseid);
 1243:         return %$returnhash if (defined($returnhash));
 1244:     }
 1245:     return ();
 1246: }
 1247: 
 1248: ################################################
 1249: ################################################
 1250: 
 1251: =pod
 1252: 
 1253: =item &get_problem_statistics()
 1254: 
 1255: Gather data on a given problem.  The database is assumed to be 
 1256: populated and all local caching variables are assumed to be set
 1257: properly.  This means you need to call &ensure_current_data for
 1258: the students you are concerned with prior to calling this routine.
 1259: 
 1260: Inputs: $students, $symb, $part, $courseid
 1261: 
 1262: =over 4
 1263: 
 1264: =item $students is an array of hash references.  
 1265: Each hash must contain at least the 'username' and 'domain' of a student.
 1266: 
 1267: =item $symb is the symb for the problem.
 1268: 
 1269: =item $part is the part id you need statistics for
 1270: 
 1271: =item $courseid is the course id, of course!
 1272: 
 1273: =back
 1274: 
 1275: Outputs: See the code for up to date information.  A hash reference is
 1276: returned.  The hash has the following keys defined:
 1277: 
 1278: =over 4
 1279: 
 1280: =item num_students The number of students attempting the problem
 1281:       
 1282: =item tries The total number of tries for the students
 1283:       
 1284: =item max_tries The maximum number of tries taken
 1285:       
 1286: =item mean_tries The average number of tries
 1287:       
 1288: =item num_solved The number of students able to solve the problem
 1289:       
 1290: =item num_override The number of students whose answer is 'correct_by_override'
 1291:       
 1292: =item deg_of_diff The degree of difficulty of the problem
 1293:       
 1294: =item std_tries The standard deviation of the number of tries
 1295:       
 1296: =item skew_tries The skew of the number of tries
 1297: 
 1298: =item per_wrong The number of students attempting the problem who were not
 1299: able to answer it correctly.
 1300: 
 1301: =back
 1302: 
 1303: =cut
 1304: 
 1305: ################################################
 1306: ################################################
 1307: sub get_problem_statistics {
 1308:     my ($students,$symb,$part,$courseid) = @_;
 1309:     return if (! defined($symb) || ! defined($part));
 1310:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
 1311:     #
 1312:     my $symb_id = &get_symb_id($symb);
 1313:     my $part_id = &get_part_id($part);
 1314:     my $stats_table = $courseid.'_problem_stats';
 1315:     #
 1316:     my $dbh = &Apache::lonmysql::get_dbh();
 1317:     return undef if (! defined($dbh));
 1318:     #
 1319:     # A) Number of Students attempting problem
 1320:     # B) Total number of tries of students attempting problem
 1321:     # C) Mod (largest number of tries for solving the problem)
 1322:     # D) Mean (average number of tries for solving the problem)
 1323:     # E) Number of students to solve the problem
 1324:     # F) Number of students to solve the problem by override
 1325:     # G) Number of students unable to solve the problem
 1326:     # H) Degree of difficulty : 1-(E+F)/B
 1327:     # I) Standard deviation of number of tries
 1328:     # J) Skew of tries: sqrt(sum(Xi-D)^3)/A
 1329:     #
 1330:     $dbh->do('DROP TABLE '.$stats_table);  # May return an error
 1331:     my $request = 
 1332:         'CREATE TEMPORARY TABLE '.$stats_table.
 1333:             ' SELECT student_id,solved,award,tries FROM '.$performance_table.
 1334:                 ' WHERE symb_id='.$symb_id.' AND part_id='.$part_id;
 1335:     if (defined($students)) {
 1336:         $request .= ' AND ('.
 1337:             join(' OR ', map {'student_id='.
 1338:                                   &get_student_id($_->{'username'},
 1339:                                                   $_->{'domain'})
 1340:                                   } @$students
 1341:                  ).')';
 1342:     }
 1343: #    &Apache::lonnet::logthis($request);
 1344:     $dbh->do($request);
 1345:     my ($num,$tries,$mod,$mean,$STD) = &execute_SQL_request
 1346:         ($dbh,
 1347:          'SELECT COUNT(*),SUM(tries),MAX(tries),AVG(tries),STD(tries) FROM '.
 1348:          $stats_table);
 1349:     my ($Solved) = &execute_SQL_request($dbh,'SELECT COUNT(tries) FROM '.
 1350:                                         $stats_table.
 1351:                                         " WHERE solved='correct_by_student'");
 1352:     my ($solved) = &execute_SQL_request($dbh,'SELECT COUNT(tries) FROM '.
 1353:                                         $stats_table.
 1354:                                         " WHERE solved='correct_by_override'");
 1355:     $num    = 0 if (! defined($num));
 1356:     $tries  = 0 if (! defined($tries));
 1357:     $mod    = 0 if (! defined($mod));
 1358:     $STD    = 0 if (! defined($STD));
 1359:     $Solved = 0 if (! defined($Solved));
 1360:     $solved = 0 if (! defined($solved));
 1361:     #
 1362:     my $DegOfDiff = 'nan';
 1363:     $DegOfDiff = 1-($Solved)/$tries if ($tries>0);
 1364: 
 1365:     my $SKEW = 'nan';
 1366:     my $wrongpercent = 0;
 1367:     if ($num > 0) {
 1368:         ($SKEW) = &execute_SQL_request($dbh,'SELECT SQRT(SUM('.
 1369:                                      'POWER(tries - '.$STD.',3)'.
 1370:                                      '))/'.$num.' FROM '.$stats_table);
 1371:         $wrongpercent=int(10*100*($num-$Solved+$solved)/$num)/10;
 1372:     }
 1373:     #
 1374:     $dbh->do('DROP TABLE '.$stats_table);  # May return an error
 1375:     return { num_students => $num,
 1376:              tries        => $tries,
 1377:              max_tries    => $mod,
 1378:              mean_tries   => $mean,
 1379:              std_tries    => $STD,
 1380:              skew_tries   => $SKEW,
 1381:              num_solved   => $Solved,
 1382:              num_override => $solved,
 1383:              per_wrong    => $wrongpercent,
 1384:              deg_of_diff  => $DegOfDiff }
 1385: }
 1386: 
 1387: sub execute_SQL_request {
 1388:     my ($dbh,$request)=@_;
 1389: #    &Apache::lonnet::logthis($request);
 1390:     my $sth = $dbh->prepare($request);
 1391:     $sth->execute();
 1392:     my $row = $sth->fetchrow_arrayref();
 1393:     if (ref($row) eq 'ARRAY' && scalar(@$row)>0) {
 1394:         return @$row;
 1395:     }
 1396:     return ();
 1397: }
 1398: 
 1399: 
 1400: ################################################
 1401: ################################################
 1402: 
 1403: =pod
 1404: 
 1405: =item &setup_table_names()
 1406: 
 1407: input: course id
 1408: 
 1409: output: none
 1410: 
 1411: Cleans up the package variables for local caching.
 1412: 
 1413: =cut
 1414: 
 1415: ################################################
 1416: ################################################
 1417: sub setup_table_names {
 1418:     my ($courseid) = @_;
 1419:     if (! defined($courseid)) {
 1420:         $courseid = $ENV{'request.course.id'};
 1421:     }
 1422:     #
 1423:     if (! defined($current_course) || $current_course ne $courseid) {
 1424:         # Clear out variables
 1425:         $have_read_part_table = 0;
 1426:         undef(%ids_by_part);
 1427:         undef(%parts_by_id);
 1428:         $have_read_symb_table = 0;
 1429:         undef(%ids_by_symb);
 1430:         undef(%symbs_by_id);
 1431:         $have_read_student_table = 0;
 1432:         undef(%ids_by_student);
 1433:         undef(%students_by_id);
 1434:         #
 1435:         $current_course = $courseid;
 1436:     }
 1437:     #
 1438:     # Set up database names
 1439:     my $base_id = $courseid;
 1440:     $symb_table        = $base_id.'_'.'symb';
 1441:     $part_table        = $base_id.'_'.'part';
 1442:     $student_table     = $base_id.'_'.'student';
 1443:     $updatetime_table  = $base_id.'_'.'updatetime';
 1444:     $performance_table = $base_id.'_'.'performance';
 1445:     $parameters_table  = $base_id.'_'.'parameters';
 1446:     return;
 1447: }
 1448: 
 1449: ################################################
 1450: ################################################
 1451: 
 1452: =pod
 1453: 
 1454: =back
 1455: 
 1456: =item End of Local Data Caching Subroutines
 1457: 
 1458: =cut
 1459: 
 1460: ################################################
 1461: ################################################
 1462: 
 1463: 
 1464: }
 1465: ################################################
 1466: ################################################
 1467: 
 1468: =pod
 1469: 
 1470: =head3 Classlist Subroutines
 1471: 
 1472: =item &get_classlist();
 1473: 
 1474: Retrieve the classist of a given class or of the current class.  Student
 1475: information is returned from the classlist.db file and, if needed,
 1476: from the students environment.
 1477: 
 1478: Optional arguments are $cid, $cdom, and $cnum (course id, course domain,
 1479: and course number, respectively).  Any omitted arguments will be taken 
 1480: from the current environment ($ENV{'request.course.id'},
 1481: $ENV{'course.'.$cid.'.domain'}, and $ENV{'course.'.$cid.'.num'}).
 1482: 
 1483: Returns a reference to a hash which contains:
 1484:  keys    '$sname:$sdom'
 1485:  values  [$sdom,$sname,$end,$start,$id,$section,$fullname,$status]
 1486: 
 1487: The constant values CL_SDOM, CL_SNAME, CL_END, etc. can be used
 1488: as indices into the returned list to future-proof clients against
 1489: changes in the list order.
 1490: 
 1491: =cut
 1492: 
 1493: ################################################
 1494: ################################################
 1495: 
 1496: sub CL_SDOM     { return 0; }
 1497: sub CL_SNAME    { return 1; }
 1498: sub CL_END      { return 2; }
 1499: sub CL_START    { return 3; }
 1500: sub CL_ID       { return 4; }
 1501: sub CL_SECTION  { return 5; }
 1502: sub CL_FULLNAME { return 6; }
 1503: sub CL_STATUS   { return 7; }
 1504: 
 1505: sub get_classlist {
 1506:     my ($cid,$cdom,$cnum) = @_;
 1507:     $cid = $cid || $ENV{'request.course.id'};
 1508:     $cdom = $cdom || $ENV{'course.'.$cid.'.domain'};
 1509:     $cnum = $cnum || $ENV{'course.'.$cid.'.num'};
 1510:     my $now = time;
 1511:     #
 1512:     my %classlist=&Apache::lonnet::dump('classlist',$cdom,$cnum);
 1513:     while (my ($student,$info) = each(%classlist)) {
 1514:         if ($student =~ /^(con_lost|error|no_such_host)/i) {
 1515:             &Apache::lonnet::logthis('get_classlist error for '.$cid.':'.$student);
 1516:             return undef;
 1517:         }
 1518:         my ($sname,$sdom) = split(/:/,$student);
 1519:         my @Values = split(/:/,$info);
 1520:         my ($end,$start,$id,$section,$fullname);
 1521:         if (@Values > 2) {
 1522:             ($end,$start,$id,$section,$fullname) = @Values;
 1523:         } else { # We have to get the data ourselves
 1524:             ($end,$start) = @Values;
 1525:             $section = &Apache::lonnet::getsection($sdom,$sname,$cid);
 1526:             my %info=&Apache::lonnet::get('environment',
 1527:                                           ['firstname','middlename',
 1528:                                            'lastname','generation','id'],
 1529:                                           $sdom, $sname);
 1530:             my ($tmp) = keys(%info);
 1531:             if ($tmp =~/^(con_lost|error|no_such_host)/i) {
 1532:                 $fullname = 'not available';
 1533:                 $id = 'not available';
 1534:                 &Apache::lonnet::logthis('unable to retrieve environment '.
 1535:                                          'for '.$sname.':'.$sdom);
 1536:             } else {
 1537:                 $fullname = &ProcessFullName(@info{qw/lastname generation 
 1538:                                                        firstname middlename/});
 1539:                 $id = $info{'id'};
 1540:             }
 1541:             # Update the classlist with this students information
 1542:             if ($fullname ne 'not available') {
 1543:                 my $enrolldata = join(':',$end,$start,$id,$section,$fullname);
 1544:                 my $reply=&Apache::lonnet::cput('classlist',
 1545:                                                 {$student => $enrolldata},
 1546:                                                 $cdom,$cnum);
 1547:                 if ($reply !~ /^(ok|delayed)/) {
 1548:                     &Apache::lonnet::logthis('Unable to update classlist for '.
 1549:                                              'student '.$sname.':'.$sdom.
 1550:                                              ' error:'.$reply);
 1551:                 }
 1552:             }
 1553:         }
 1554:         my $status='Expired';
 1555:         if(((!$end) || $now < $end) && ((!$start) || ($now > $start))) {
 1556:             $status='Active';
 1557:         }
 1558:         $classlist{$student} = 
 1559:             [$sdom,$sname,$end,$start,$id,$section,$fullname,$status];
 1560:     }
 1561:     if (wantarray()) {
 1562:         return (\%classlist,['domain','username','end','start','id',
 1563:                              'section','fullname','status']);
 1564:     } else {
 1565:         return \%classlist;
 1566:     }
 1567: }
 1568: 
 1569: # ----- END HELPER FUNCTIONS --------------------------------------------
 1570: 
 1571: 1;
 1572: __END__
 1573: 
 1574: 

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