File:  [LON-CAPA] / loncom / interface / loncoursedata.pm
Revision 1.132: download - view: text, annotated - select for diffs
Fri Apr 30 14:36:52 2004 UTC (20 years, 1 month ago) by matthew
Branches: MAIN
CVS tags: HEAD
Bug 2954: MySQL CHAR/VARCHAR are case insensitive by default, so use
'BINARY' to make them behave the way we expect.

    1: # The LearningOnline Network with CAPA
    2: #
    3: # $Id: loncoursedata.pm,v 1.132 2004/04/30 14:36:52 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: Use lonnavmaps to build a data structure describing the order and 
   77: assessment contents of each sequence in the current course.
   78: 
   79: The returned structure is a hash reference. 
   80: 
   81: { title => 'title',
   82:   symb  => 'symb',
   83:   src   => '/s/o/u/r/c/e',
   84:   type  => (container|assessment),
   85:   num_assess   => 2,               # only for container
   86:   parts        => [11,13,15],      # only for assessment
   87:   response_ids => [12,14,16],      # only for assessment
   88:   contents     => [........]       # only for container
   89: }
   90: 
   91: $hash->{'contents'} is a reference to an array of hashes of the same structure.
   92: 
   93: Also returned are array references to the sequences and assessments contained
   94: in the course.
   95: 
   96: 
   97: =cut
   98: 
   99: ####################################################
  100: ####################################################
  101: sub get_sequence_assessment_data {
  102:     my $fn=$ENV{'request.course.fn'};
  103:     ##
  104:     ## use navmaps
  105:     my $navmap = Apache::lonnavmaps::navmap->new();
  106:     if (!defined($navmap)) {
  107:         return 'Can not open Coursemap';
  108:     }
  109:     # We explicity grab the top level map because I am not sure we
  110:     # are pulling it from the iterator.
  111:     my $top_level_map = $navmap->getById('0.0');
  112:     #
  113:     my $iterator = $navmap->getIterator(undef, undef, undef, 1);
  114:     my $curRes = $iterator->next(); # Top level sequence
  115:     ##
  116:     ## Prime the pump 
  117:     ## 
  118:     ## We are going to loop until we run out of sequences/pages to explore for
  119:     ## resources.  This means we have to start out with something to look
  120:     ## at.
  121:     my $title = $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
  122:     my $symb  = $top_level_map->symb();
  123:     my $src   = $top_level_map->src();
  124:     my $randompick = $top_level_map->randompick();
  125:     #
  126:     my @Sequences; 
  127:     my @Assessments;
  128:     my @Nested_Sequences = ();   # Stack of sequences, keeps track of depth
  129:     my $top = { title    => $title,
  130:                 src      => $src,
  131:                 symb     => $symb,
  132:                 type     => 'container',
  133:                 num_assess => 0,
  134:                 num_assess_parts => 0,
  135:                 contents   => [], 
  136:                 randompick => $randompick,
  137:             };
  138:     push (@Sequences,$top);
  139:     push (@Nested_Sequences, $top);
  140:     #
  141:     # We need to keep track of which sequences contain homework problems
  142:     # 
  143:     my $previous_too;
  144:     my $previous;
  145:     while (scalar(@Nested_Sequences)) {
  146:         $previous_too = $previous;
  147:         $previous = $curRes;
  148:         $curRes = $iterator->next();
  149:         my $currentmap = $Nested_Sequences[-1]; # Last one on the stack
  150:         if ($curRes == $iterator->BEGIN_MAP()) {
  151:             if (! ref($previous)) {
  152:                 $previous = $previous_too;
  153:             }
  154:             if (! ref($previous)) {
  155:                 next;
  156:             }
  157:             # get the map itself, instead of BEGIN_MAP
  158:             $title = $previous->title();
  159:             $title =~ s/\:/\&\#058;/g;
  160:             $symb  = $previous->symb();
  161:             $src   = $previous->src();
  162:             # pick up the filename if there is no title available
  163:             if (! defined($title) || $title eq '') {
  164:                 ($title) = ($src=~/\/([^\/]*)$/);
  165:             }
  166:             $randompick = $previous->randompick();
  167:             my $newmap = { title    => $title,
  168:                            src      => $src,
  169:                            symb     => $symb,
  170:                            type     => 'container',
  171:                            num_assess => 0,
  172:                            randompick => $randompick,
  173:                            contents   => [],
  174:                        };
  175:             push (@{$currentmap->{'contents'}},$newmap); # this is permanent
  176:             push (@Sequences,$newmap);
  177:             push (@Nested_Sequences, $newmap); # this is a stack
  178:             next;
  179:         }
  180:         if ($curRes == $iterator->END_MAP()) {
  181:             pop(@Nested_Sequences);
  182:             next;
  183:         }
  184:         next if (! ref($curRes));
  185:         next if (! $curRes->is_problem() && $curRes->src() !~ /\.survey$/);
  186:         # Okay, from here on out we only deal with assessments
  187:         $title = $curRes->title();
  188:         $title =~ s/\:/\&\#058;/g;
  189:         $symb  = $curRes->symb();
  190:         $src   = $curRes->src();
  191:         # Grab the filename if there is not title available
  192:         if (! defined($title) || $title eq '') {
  193:             ($title) = ($src=~ m:/([^/]*)$:);
  194:         }
  195:         my $parts = $curRes->parts();
  196:         my %partdata;
  197:         foreach my $part (@$parts) {
  198:             my @Responses = $curRes->responseType($part);
  199:             my @Ids       = $curRes->responseIds($part);
  200:             $partdata{$part}->{'ResponseTypes'}= \@Responses;
  201:             $partdata{$part}->{'ResponseIds'}  = \@Ids;
  202:             # Count how many responses of each type there are in this part
  203:             foreach (@Responses) {
  204:                 $partdata{$part}->{$_}++;
  205:             }
  206:         }
  207:         my $assessment = { title => $title,
  208:                            src   => $src,
  209:                            symb  => $symb,
  210:                            type  => 'assessment',
  211:                            parts => $parts,
  212:                            num_parts => scalar(@$parts),
  213:                            partdata => \%partdata,
  214:                        };
  215:         push(@Assessments,$assessment);
  216:         push(@{$currentmap->{'contents'}},$assessment);
  217:         $currentmap->{'num_assess'}++;
  218:         $currentmap->{'num_assess_parts'}+= scalar(@$parts);
  219:     }
  220:     $navmap->untieHashes();
  221:     return ($top,\@Sequences,\@Assessments);
  222: }
  223: 
  224: sub LoadDiscussion {
  225:     my ($courseID)=@_;
  226:     my %Discuss=();
  227:     my %contrib=&Apache::lonnet::dump(
  228:                 $courseID,
  229:                 $ENV{'course.'.$courseID.'.domain'},
  230:                 $ENV{'course.'.$courseID.'.num'});
  231: 				 
  232:     #my %contrib=&DownloadCourseInformation($name, $courseID, 0);
  233: 
  234:     foreach my $temp(keys %contrib) {
  235: 	if ($temp=~/^version/) {
  236: 	    my $ver=$contrib{$temp};
  237: 	    my ($dummy,$prb)=split(':',$temp);
  238: 	    for (my $idx=1; $idx<=$ver; $idx++ ) {
  239: 		my $name=$contrib{"$idx:$prb:sendername"};
  240: 		$Discuss{"$name:$prb"}=$idx;	
  241: 	    }
  242: 	}
  243:     }       
  244: 
  245:     return \%Discuss;
  246: }
  247: 
  248: ################################################
  249: ################################################
  250: 
  251: =pod
  252: 
  253: =item &GetUserName(username,userdomain)
  254: 
  255: Returns a hash with the following entries:
  256:    'firstname', 'middlename', 'lastname', 'generation', and 'fullname'
  257: 
  258:    'fullname' is the result of &Apache::loncoursedata::ProcessFullName.
  259: 
  260: =cut
  261: 
  262: ################################################
  263: ################################################
  264: sub GetUserName {
  265:     my ($username,$userdomain) = @_;
  266:     $username = $ENV{'user.name'} if (! defined($username));
  267:     $userdomain = $ENV{'user.domain'} if (! defined($username));
  268:     my %userenv = &Apache::lonnet::get('environment',
  269:                            ['firstname','middlename','lastname','generation'],
  270:                                        $userdomain,$username);
  271:     $userenv{'fullname'} = &ProcessFullName($userenv{'lastname'},
  272:                                             $userenv{'generation'},
  273:                                             $userenv{'firstname'},
  274:                                             $userenv{'middlename'});
  275:     return %userenv;
  276: }
  277: 
  278: ################################################
  279: ################################################
  280: 
  281: =pod
  282: 
  283: =item &ProcessFullName()
  284: 
  285: Takes lastname, generation, firstname, and middlename (or some partial
  286: set of this data) and returns the full name version as a string.  Format
  287: is Lastname generation, firstname middlename or a subset of this.
  288: 
  289: =cut
  290: 
  291: ################################################
  292: ################################################
  293: sub ProcessFullName {
  294:     my ($lastname, $generation, $firstname, $middlename)=@_;
  295:     my $Str = '';
  296: 
  297:     # Strip whitespace preceeding & following name components.
  298:     $lastname   =~ s/(\s+$|^\s+)//g;
  299:     $generation =~ s/(\s+$|^\s+)//g;
  300:     $firstname  =~ s/(\s+$|^\s+)//g;
  301:     $middlename =~ s/(\s+$|^\s+)//g;
  302: 
  303:     if($lastname ne '') {
  304: 	$Str .= $lastname;
  305: 	$Str .= ' '.$generation if ($generation ne '');
  306: 	$Str .= ',';
  307:         $Str .= ' '.$firstname  if ($firstname ne '');
  308:         $Str .= ' '.$middlename if ($middlename ne '');
  309:     } else {
  310:         $Str .= $firstname      if ($firstname ne '');
  311:         $Str .= ' '.$middlename if ($middlename ne '');
  312:         $Str .= ' '.$generation if ($generation ne '');
  313:     }
  314: 
  315:     return $Str;
  316: }
  317: 
  318: ################################################
  319: ################################################
  320: 
  321: =pod
  322: 
  323: =item &make_into_hash($values);
  324: 
  325: Returns a reference to a hash as described by $values.  $values is
  326: assumed to be the result of 
  327:     join(':',map {&Apache::lonnet::escape($_)} %orighash);
  328: 
  329: This is a helper function for get_current_state.
  330: 
  331: =cut
  332: 
  333: ################################################
  334: ################################################
  335: sub make_into_hash {
  336:     my $values = shift;
  337:     my %tmp = map { &Apache::lonnet::unescape($_); }
  338:                                            split(':',$values);
  339:     return \%tmp;
  340: }
  341: 
  342: 
  343: ################################################
  344: ################################################
  345: 
  346: =pod
  347: 
  348: =head1 LOCAL DATA CACHING SUBROUTINES
  349: 
  350: The local caching is done using MySQL.  There is no fall-back implementation
  351: if MySQL is not running.
  352: 
  353: The programmers interface is to call &get_current_state() or some other
  354: primary interface subroutine (described below).  The internals of this 
  355: storage system are documented here.
  356: 
  357: There are six tables used to store student performance data (the results of
  358: a dumpcurrent).  Each of these tables is created in MySQL with a name of
  359: $courseid_*****, where ***** is 'symb', 'part', or whatever is appropriate 
  360: for the table.  The tables and their purposes are described below.
  361: 
  362: Some notes before we get started.
  363: 
  364: Each table must have a PRIMARY KEY, which is a column or set of columns which
  365: will serve to uniquely identify a row of data.  NULL is not allowed!
  366: 
  367: INDEXes work best on integer data.
  368: 
  369: JOIN is used to combine data from many tables into one output.
  370: 
  371: lonmysql.pm is used for some of the interface, specifically the table creation
  372: calls.  The inserts are done in bulk by directly calling the database handler.
  373: The SELECT ... JOIN statement used to retrieve the data does not have an
  374: interface in lonmysql.pm and I shudder at the thought of writing one.
  375: 
  376: =head3 Table Descriptions
  377: 
  378: =over 4
  379: 
  380: =item Tables used to store meta information
  381: 
  382: The following tables hold data required to keep track of the current status
  383: of a students data in the tables or to look up the students data in the tables.
  384: 
  385: =over 4
  386: 
  387: =item $symb_table
  388: 
  389: The symb_table has two columns.  The first is a 'symb_id' and the second
  390: is the text name for the 'symb' (limited to 64k).  The 'symb_id' is generated
  391: automatically by MySQL so inserts should be done on this table with an
  392: empty first element.  This table has its PRIMARY KEY on the 'symb_id'.
  393: 
  394: =item $part_table
  395: 
  396: The part_table has two columns.  The first is a 'part_id' and the second
  397: is the text name for the 'part' (limited to 100 characters).  The 'part_id' is
  398: generated automatically by MySQL so inserts should be done on this table with
  399: an empty first element.  This table has its PRIMARY KEY on the 'part' (100
  400: characters) and a KEY on 'part_id'.
  401: 
  402: =item $student_table
  403: 
  404: The student_table has 7 columns.  The first is a 'student_id' assigned by 
  405: MySQL.  The second is 'student' which is username:domain.  The third through
  406: fifth are 'section', 'status' (enrollment status), and 'classification' 
  407: (to be used in the future).  The sixth and seventh ('updatetime' and 
  408: 'fullupdatetime') contain the time of last update and full update of student
  409: data.  This table has its PRIMARY KEY on the 'student_id' column and is indexed
  410: on 'student', 'section', and 'status'.
  411: 
  412: =back 
  413: 
  414: =item Tables used to store current status data
  415: 
  416: The following tables store data only about the students current status on 
  417: a problem, meaning only the data related to the last attempt on a problem.
  418: 
  419: =over 4
  420: 
  421: =item $performance_table
  422: 
  423: The performance_table has 9 columns.  The first three are 'symb_id', 
  424: 'student_id', and 'part_id'.  These comprise the PRIMARY KEY for this table
  425: and are directly related to the $symb_table, $student_table, and $part_table
  426: described above.  MySQL does better indexing on numeric items than text,
  427: so we use these three "index tables".  The remaining columns are
  428: 'solved', 'tries', 'awarded', 'award', 'awarddetail', and 'timestamp'.
  429: These are either the MySQL type TINYTEXT or various integers ('tries' and 
  430: 'timestamp').  This table has KEYs of 'student_id' and 'symb_id'.
  431: For use of this table, see the functions described below.
  432: 
  433: =item $parameters_table
  434: 
  435: The parameters_table holds the data that does not fit neatly into the
  436: performance_table.  The parameters table has four columns: 'symb_id',
  437: 'student_id', 'parameter', and 'value'.  'symb_id', 'student_id', and
  438: 'parameter' comprise the PRIMARY KEY for this table.  'parameter' is 
  439: limited to 255 characters.  'value' is limited to 64k characters.
  440: 
  441: =back
  442: 
  443: =item Tables used for storing historic data
  444: 
  445: The following tables are used to store almost all of the transactions a student
  446: has made on a homework problem.  See loncapa/docs/homework/datastorage for 
  447: specific information about each of the parameters stored.  
  448: 
  449: =over 4
  450: 
  451: =item $fulldump_response_table
  452: 
  453: The response table holds data (documented in loncapa/docs/homework/datastorage)
  454: associated with a particular response id which is stored when a student 
  455: attempts a problem.  The following are the columns of the table, in order:
  456: 'symb_id','part_id','response_id','student_id','transaction','tries',
  457: 'awarddetail', 'response_specific' (data particular to the response
  458: type), 'response_specific_value', and 'submission (the text of the students
  459: submission).  The primary key is based on the first five columns listed above.
  460: 
  461: =item $fulldump_part_table
  462: 
  463: The part table holds data (documented in loncapa/docs/homework/datastorage)
  464: associated with a particular part id which is stored when a student attempts
  465: a problem.  The following are the columns of the table, in order:
  466: 'symb_id','part_id','student_id','transaction','tries','award','awarded',
  467: and 'previous'.  The primary key is based on the first five columns listed 
  468: above.
  469: 
  470: =item $fulldump_timestamp_table
  471: 
  472: The timestamp table holds the timestamps of the transactions which are
  473: stored in $fulldump_response_table and $fulldump_part_table.  This data is
  474: about both the response and part data.  Columns: 'symb_id','student_id',
  475: 'transaction', and 'timestamp'.  
  476: The primary key is based on the first 3 columns.
  477: 
  478: =item $weight_table
  479: 
  480: The weight table holds the weight for the problems used in the class.
  481: Whereas the weight of a problem can vary by section and student the data
  482: here is applied to the class as a whole.
  483: Columns: 'symb_id','part_id','response_id','weight'.
  484: 
  485: =back
  486: 
  487: =back
  488: 
  489: =head3 Important Subroutines
  490: 
  491: Here is a brief overview of the subroutines which are likely to be of 
  492: interest:
  493: 
  494: =over 4
  495: 
  496: =item &get_current_state(): programmers interface.
  497: 
  498: =item &init_dbs(): table creation
  499: 
  500: =item &update_student_data(): data storage calls
  501: 
  502: =item &get_student_data_from_performance_cache(): data retrieval
  503: 
  504: =back
  505: 
  506: =head3 Main Documentation
  507: 
  508: =over 4
  509: 
  510: =cut
  511: 
  512: ################################################
  513: ################################################
  514: 
  515: ################################################
  516: ################################################
  517: { # Begin scope of table identifiers
  518: 
  519: my $current_course ='';
  520: my $symb_table;
  521: my $part_table;
  522: my $student_table;
  523: my $performance_table;
  524: my $parameters_table;
  525: my $fulldump_response_table;
  526: my $fulldump_part_table;
  527: my $fulldump_timestamp_table;
  528: my $weight_table;
  529: 
  530: my @Tables;
  531: ################################################
  532: ################################################
  533: 
  534: =pod
  535: 
  536: =item &init_dbs()
  537: 
  538: Input: course id
  539: 
  540: Output: 0 on success, positive integer on error
  541: 
  542: This routine issues the calls to lonmysql to create the tables used to
  543: store student data.
  544: 
  545: =cut
  546: 
  547: ################################################
  548: ################################################
  549: sub init_dbs {
  550:     my $courseid = shift;
  551:     &setup_table_names($courseid);
  552:     #
  553:     # Drop any of the existing tables
  554:     foreach my $table (@Tables) {
  555:         &Apache::lonmysql::drop_table($table);
  556:     }
  557:     #
  558:     # Note - changes to this table must be reflected in the code that 
  559:     # stores the data (calls &Apache::lonmysql::store_row with this table
  560:     # id
  561:     my $symb_table_def = {
  562:         id => $symb_table,
  563:         permanent => 'no',
  564:         columns => [{ name => 'symb_id',
  565:                       type => 'MEDIUMINT UNSIGNED',
  566:                       restrictions => 'NOT NULL',
  567:                       auto_inc     => 'yes', },
  568:                     { name => 'symb',
  569:                       type => 'MEDIUMTEXT',
  570:                       restrictions => 'NOT NULL'},
  571:                     ],
  572:         'PRIMARY KEY' => ['symb_id'],
  573:     };
  574:     #
  575:     my $part_table_def = {
  576:         id => $part_table,
  577:         permanent => 'no',
  578:         columns => [{ name => 'part_id',
  579:                       type => 'MEDIUMINT UNSIGNED',
  580:                       restrictions => 'NOT NULL',
  581:                       auto_inc     => 'yes', },
  582:                     { name => 'part',
  583:                       type => 'VARCHAR(100) BINARY',
  584:                       restrictions => 'NOT NULL'},
  585:                     ],
  586:         'PRIMARY KEY' => ['part (100)'],
  587:         'KEY' => [{ columns => ['part_id']},],
  588:     };
  589:     #
  590:     my $student_table_def = {
  591:         id => $student_table,
  592:         permanent => 'no',
  593:         columns => [{ name => 'student_id',
  594:                       type => 'MEDIUMINT UNSIGNED',
  595:                       restrictions => 'NOT NULL',
  596:                       auto_inc     => 'yes', },
  597:                     { name => 'student',
  598:                       type => 'VARCHAR(100) BINARY',
  599:                       restrictions => 'NOT NULL UNIQUE'},
  600:                     { name => 'section',
  601:                       type => 'VARCHAR(100) BINARY',
  602:                       restrictions => 'NOT NULL'},
  603:                     { name => 'status',
  604:                       type => 'VARCHAR(15) BINARY',
  605:                       restrictions => 'NOT NULL'},
  606:                     { name => 'classification',
  607:                       type => 'VARCHAR(100) BINARY', },
  608:                     { name => 'updatetime',
  609:                       type => 'INT UNSIGNED'},
  610:                     { name => 'fullupdatetime',
  611:                       type => 'INT UNSIGNED'},
  612:                     ],
  613:         'PRIMARY KEY' => ['student_id'],
  614:         'KEY' => [{ columns => ['student (100)',
  615:                                 'section (100)',
  616:                                 'status (15)',]},],
  617:     };
  618:     #
  619:     my $performance_table_def = {
  620:         id => $performance_table,
  621:         permanent => 'no',
  622:         columns => [{ name => 'symb_id',
  623:                       type => 'MEDIUMINT UNSIGNED',
  624:                       restrictions => 'NOT NULL'  },
  625:                     { name => 'student_id',
  626:                       type => 'MEDIUMINT UNSIGNED',
  627:                       restrictions => 'NOT NULL'  },
  628:                     { name => 'part_id',
  629:                       type => 'MEDIUMINT UNSIGNED',
  630:                       restrictions => 'NOT NULL' },
  631:                     { name => 'part',
  632:                       type => 'VARCHAR(100) BINARY',
  633:                       restrictions => 'NOT NULL'},                    
  634:                     { name => 'solved',
  635:                       type => 'TINYTEXT' },
  636:                     { name => 'tries',
  637:                       type => 'SMALLINT UNSIGNED' },
  638:                     { name => 'awarded',
  639:                       type => 'REAL' },
  640:                     { name => 'award',
  641:                       type => 'TINYTEXT' },
  642:                     { name => 'awarddetail',
  643:                       type => 'TINYTEXT' },
  644:                     { name => 'timestamp',
  645:                       type => 'INT UNSIGNED'},
  646:                     ],
  647:         'PRIMARY KEY' => ['symb_id','student_id','part_id'],
  648:         'KEY' => [{ columns=>['student_id'] },
  649:                   { columns=>['symb_id'] },],
  650:     };
  651:     #
  652:     my $fulldump_part_table_def = {
  653:         id => $fulldump_part_table,
  654:         permanent => 'no',
  655:         columns => [
  656:                     { name => 'symb_id',
  657:                       type => 'MEDIUMINT UNSIGNED',
  658:                       restrictions => 'NOT NULL'  },
  659:                     { name => 'part_id',
  660:                       type => 'MEDIUMINT UNSIGNED',
  661:                       restrictions => 'NOT NULL' },
  662:                     { name => 'student_id',
  663:                       type => 'MEDIUMINT UNSIGNED',
  664:                       restrictions => 'NOT NULL'  },
  665:                     { name => 'transaction',
  666:                       type => 'MEDIUMINT UNSIGNED',
  667:                       restrictions => 'NOT NULL' },
  668:                     { name => 'tries',
  669:                       type => 'SMALLINT UNSIGNED',
  670:                       restrictions => 'NOT NULL' },
  671:                     { name => 'award',
  672:                       type => 'TINYTEXT' },
  673:                     { name => 'awarded',
  674:                       type => 'REAL' },
  675:                     { name => 'previous',
  676:                       type => 'SMALLINT UNSIGNED' },
  677: #                    { name => 'regrader',
  678: #                      type => 'TINYTEXT' },
  679: #                    { name => 'afterduedate',
  680: #                      type => 'TINYTEXT' },
  681:                     ],
  682:         'PRIMARY KEY' => ['symb_id','part_id','student_id','transaction'],
  683:         'KEY' => [
  684:                   { columns=>['symb_id'] },
  685:                   { columns=>['part_id'] },
  686:                   { columns=>['student_id'] },
  687:                   ],
  688:     };
  689:     #
  690:     my $fulldump_response_table_def = {
  691:         id => $fulldump_response_table,
  692:         permanent => 'no',
  693:         columns => [
  694:                     { name => 'symb_id',
  695:                       type => 'MEDIUMINT UNSIGNED',
  696:                       restrictions => 'NOT NULL'  },
  697:                     { name => 'part_id',
  698:                       type => 'MEDIUMINT UNSIGNED',
  699:                       restrictions => 'NOT NULL' },
  700:                     { name => 'response_id',
  701:                       type => 'MEDIUMINT UNSIGNED',
  702:                       restrictions => 'NOT NULL'  },
  703:                     { name => 'student_id',
  704:                       type => 'MEDIUMINT UNSIGNED',
  705:                       restrictions => 'NOT NULL'  },
  706:                     { name => 'transaction',
  707:                       type => 'MEDIUMINT UNSIGNED',
  708:                       restrictions => 'NOT NULL' },
  709:                     { name => 'awarddetail',
  710:                       type => 'TINYTEXT' },
  711: #                    { name => 'message',
  712: #                      type => 'CHAR BINARY'},
  713:                     { name => 'response_specific',
  714:                       type => 'TINYTEXT' },
  715:                     { name => 'response_specific_value',
  716:                       type => 'TINYTEXT' },
  717:                     { name => 'submission',
  718:                       type => 'TEXT'},
  719:                     ],
  720:             'PRIMARY KEY' => ['symb_id','part_id','response_id','student_id',
  721:                               'transaction'],
  722:             'KEY' => [
  723:                       { columns=>['symb_id'] },
  724:                       { columns=>['part_id','response_id'] },
  725:                       { columns=>['student_id'] },
  726:                       ],
  727:     };
  728:     my $fulldump_timestamp_table_def = {
  729:         id => $fulldump_timestamp_table,
  730:         permanent => 'no',
  731:         columns => [
  732:                     { name => 'symb_id',
  733:                       type => 'MEDIUMINT UNSIGNED',
  734:                       restrictions => 'NOT NULL'  },
  735:                     { name => 'student_id',
  736:                       type => 'MEDIUMINT UNSIGNED',
  737:                       restrictions => 'NOT NULL'  },
  738:                     { name => 'transaction',
  739:                       type => 'MEDIUMINT UNSIGNED',
  740:                       restrictions => 'NOT NULL' },
  741:                     { name => 'timestamp',
  742:                       type => 'INT UNSIGNED'},
  743:                     ],
  744:         'PRIMARY KEY' => ['symb_id','student_id','transaction'],
  745:         'KEY' => [
  746:                   { columns=>['symb_id'] },
  747:                   { columns=>['student_id'] },
  748:                   { columns=>['transaction'] },
  749:                   ],
  750:     };
  751:     #
  752:     my $parameters_table_def = {
  753:         id => $parameters_table,
  754:         permanent => 'no',
  755:         columns => [{ name => 'symb_id',
  756:                       type => 'MEDIUMINT UNSIGNED',
  757:                       restrictions => 'NOT NULL'  },
  758:                     { name => 'student_id',
  759:                       type => 'MEDIUMINT UNSIGNED',
  760:                       restrictions => 'NOT NULL'  },
  761:                     { name => 'parameter',
  762:                       type => 'TINYTEXT',
  763:                       restrictions => 'NOT NULL'  },
  764:                     { name => 'value',
  765:                       type => 'MEDIUMTEXT' },
  766:                     ],
  767:         'PRIMARY KEY' => ['symb_id','student_id','parameter (255)'],
  768:     };
  769:     #
  770:     my $weight_table_def = {
  771:         id => $weight_table,
  772:         permanent => 'no',
  773:         columns => [{ name => 'symb_id',
  774:                       type => 'MEDIUMINT UNSIGNED',
  775:                       restrictions => 'NOT NULL'  },
  776:                     { name => 'part_id',
  777:                       type => 'MEDIUMINT UNSIGNED',
  778:                       restrictions => 'NOT NULL'  },
  779:                     { name => 'weight',
  780:                       type => 'REAL',
  781:                       restrictions => 'NOT NULL'  },
  782:                     ],
  783:         'PRIMARY KEY' => ['symb_id','part_id'],
  784:     };
  785:     #
  786:     # Create the tables
  787:     my $tableid;
  788:     $tableid = &Apache::lonmysql::create_table($symb_table_def);
  789:     if (! defined($tableid)) {
  790:         &Apache::lonnet::logthis("error creating symb_table: ".
  791:                                  &Apache::lonmysql::get_error());
  792:         return 1;
  793:     }
  794:     #
  795:     $tableid = &Apache::lonmysql::create_table($part_table_def);
  796:     if (! defined($tableid)) {
  797:         &Apache::lonnet::logthis("error creating part_table: ".
  798:                                  &Apache::lonmysql::get_error());
  799:         return 2;
  800:     }
  801:     #
  802:     $tableid = &Apache::lonmysql::create_table($student_table_def);
  803:     if (! defined($tableid)) {
  804:         &Apache::lonnet::logthis("error creating student_table: ".
  805:                                  &Apache::lonmysql::get_error());
  806:         return 3;
  807:     }
  808:     #
  809:     $tableid = &Apache::lonmysql::create_table($performance_table_def);
  810:     if (! defined($tableid)) {
  811:         &Apache::lonnet::logthis("error creating preformance_table: ".
  812:                                  &Apache::lonmysql::get_error());
  813:         return 5;
  814:     }
  815:     #
  816:     $tableid = &Apache::lonmysql::create_table($parameters_table_def);
  817:     if (! defined($tableid)) {
  818:         &Apache::lonnet::logthis("error creating parameters_table: ".
  819:                                  &Apache::lonmysql::get_error());
  820:         return 6;
  821:     }
  822:     #
  823:     $tableid = &Apache::lonmysql::create_table($fulldump_part_table_def);
  824:     if (! defined($tableid)) {
  825:         &Apache::lonnet::logthis("error creating fulldump_part_table: ".
  826:                                  &Apache::lonmysql::get_error());
  827:         return 7;
  828:     }
  829:     #
  830:     $tableid = &Apache::lonmysql::create_table($fulldump_response_table_def);
  831:     if (! defined($tableid)) {
  832:         &Apache::lonnet::logthis("error creating fulldump_response_table: ".
  833:                                  &Apache::lonmysql::get_error());
  834:         return 8;
  835:     }
  836:     $tableid = &Apache::lonmysql::create_table($fulldump_timestamp_table_def);
  837:     if (! defined($tableid)) {
  838:         &Apache::lonnet::logthis("error creating fulldump_timestamp_table: ".
  839:                                  &Apache::lonmysql::get_error());
  840:         return 9;
  841:     }
  842:     $tableid = &Apache::lonmysql::create_table($weight_table_def);
  843:     if (! defined($tableid)) {
  844:         &Apache::lonnet::logthis("error creating weight_table: ".
  845:                                  &Apache::lonmysql::get_error());
  846:         return 10;
  847:     }
  848:     return 0;
  849: }
  850: 
  851: ################################################
  852: ################################################
  853: 
  854: =pod
  855: 
  856: =item &delete_caches()
  857: 
  858: =cut
  859: 
  860: ################################################
  861: ################################################
  862: sub delete_caches {
  863:     my $courseid = shift;
  864:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
  865:     #
  866:     &setup_table_names($courseid);
  867:     #
  868:     my $dbh = &Apache::lonmysql::get_dbh();
  869:     foreach my $table (@Tables) {
  870:         my $command = 'DROP TABLE '.$table.';';
  871:         $dbh->do($command);
  872:         if ($dbh->err) {
  873:             &Apache::lonnet::logthis($command.' resulted in error: '.$dbh->errstr);
  874:         }
  875:     }
  876:     return;
  877: }
  878: 
  879: ################################################
  880: ################################################
  881: 
  882: =pod
  883: 
  884: =item &get_part_id()
  885: 
  886: Get the MySQL id of a problem part string.
  887: 
  888: Input: $part
  889: 
  890: Output: undef on error, integer $part_id on success.
  891: 
  892: =item &get_part()
  893: 
  894: Get the string describing a part from the MySQL id of the problem part.
  895: 
  896: Input: $part_id
  897: 
  898: Output: undef on error, $part string on success.
  899: 
  900: =cut
  901: 
  902: ################################################
  903: ################################################
  904: 
  905: my $have_read_part_table = 0;
  906: my %ids_by_part;
  907: my %parts_by_id;
  908: 
  909: sub get_part_id {
  910:     my ($part) = @_;
  911:     $part = 0 if (! defined($part));
  912:     if (! $have_read_part_table) {
  913:         my @Result = &Apache::lonmysql::get_rows($part_table);
  914:         foreach (@Result) {
  915:             $ids_by_part{$_->[1]}=$_->[0];
  916:         }
  917:         $have_read_part_table = 1;
  918:     }
  919:     if (! exists($ids_by_part{$part})) {
  920:         &Apache::lonmysql::store_row($part_table,[undef,$part]);
  921:         undef(%ids_by_part);
  922:         my @Result = &Apache::lonmysql::get_rows($part_table);
  923:         foreach (@Result) {
  924:             $ids_by_part{$_->[1]}=$_->[0];
  925:         }
  926:     }
  927:     return $ids_by_part{$part} if (exists($ids_by_part{$part}));
  928:     return undef; # error
  929: }
  930: 
  931: sub get_part {
  932:     my ($part_id) = @_;
  933:     if (! exists($parts_by_id{$part_id})  || 
  934:         ! defined($parts_by_id{$part_id}) ||
  935:         $parts_by_id{$part_id} eq '') {
  936:         my @Result = &Apache::lonmysql::get_rows($part_table);
  937:         foreach (@Result) {
  938:             $parts_by_id{$_->[0]}=$_->[1];
  939:         }
  940:     }
  941:     return $parts_by_id{$part_id} if(exists($parts_by_id{$part_id}));
  942:     return undef; # error
  943: }
  944: 
  945: ################################################
  946: ################################################
  947: 
  948: =pod
  949: 
  950: =item &get_symb_id()
  951: 
  952: Get the MySQL id of a symb.
  953: 
  954: Input: $symb
  955: 
  956: Output: undef on error, integer $symb_id on success.
  957: 
  958: =item &get_symb()
  959: 
  960: Get the symb associated with a MySQL symb_id.
  961: 
  962: Input: $symb_id
  963: 
  964: Output: undef on error, $symb on success.
  965: 
  966: =cut
  967: 
  968: ################################################
  969: ################################################
  970: 
  971: my $have_read_symb_table = 0;
  972: my %ids_by_symb;
  973: my %symbs_by_id;
  974: 
  975: sub get_symb_id {
  976:     my ($symb) = @_;
  977:     if (! $have_read_symb_table) {
  978:         my @Result = &Apache::lonmysql::get_rows($symb_table);
  979:         foreach (@Result) {
  980:             $ids_by_symb{$_->[1]}=$_->[0];
  981:         }
  982:         $have_read_symb_table = 1;
  983:     }
  984:     if (! exists($ids_by_symb{$symb})) {
  985:         &Apache::lonmysql::store_row($symb_table,[undef,$symb]);
  986:         undef(%ids_by_symb);
  987:         my @Result = &Apache::lonmysql::get_rows($symb_table);
  988:         foreach (@Result) {
  989:             $ids_by_symb{$_->[1]}=$_->[0];
  990:         }
  991:     }
  992:     return $ids_by_symb{$symb} if(exists( $ids_by_symb{$symb}));
  993:     return undef; # error
  994: }
  995: 
  996: sub get_symb {
  997:     my ($symb_id) = @_;
  998:     if (! exists($symbs_by_id{$symb_id})  || 
  999:         ! defined($symbs_by_id{$symb_id}) ||
 1000:         $symbs_by_id{$symb_id} eq '') {
 1001:         my @Result = &Apache::lonmysql::get_rows($symb_table);
 1002:         foreach (@Result) {
 1003:             $symbs_by_id{$_->[0]}=$_->[1];
 1004:         }
 1005:     }
 1006:     return $symbs_by_id{$symb_id} if(exists( $symbs_by_id{$symb_id}));
 1007:     return undef; # error
 1008: }
 1009: 
 1010: ################################################
 1011: ################################################
 1012: 
 1013: =pod
 1014: 
 1015: =item &get_student_id()
 1016: 
 1017: Get the MySQL id of a student.
 1018: 
 1019: Input: $sname, $dom
 1020: 
 1021: Output: undef on error, integer $student_id on success.
 1022: 
 1023: =item &get_student()
 1024: 
 1025: Get student username:domain associated with the MySQL student_id.
 1026: 
 1027: Input: $student_id
 1028: 
 1029: Output: undef on error, string $student (username:domain) on success.
 1030: 
 1031: =cut
 1032: 
 1033: ################################################
 1034: ################################################
 1035: 
 1036: my $have_read_student_table = 0;
 1037: my %ids_by_student;
 1038: my %students_by_id;
 1039: 
 1040: sub get_student_id {
 1041:     my ($sname,$sdom) = @_;
 1042:     my $student = $sname.':'.$sdom;
 1043:     if (! $have_read_student_table) {
 1044:         my @Result = &Apache::lonmysql::get_rows($student_table);
 1045:         foreach (@Result) {
 1046:             $ids_by_student{$_->[1]}=$_->[0];
 1047:         }
 1048:         $have_read_student_table = 1;
 1049:     }
 1050:     if (! exists($ids_by_student{$student})) {
 1051:         &populate_student_table();
 1052:         undef(%ids_by_student);
 1053:         undef(%students_by_id);
 1054:         my @Result = &Apache::lonmysql::get_rows($student_table);
 1055:         foreach (@Result) {
 1056:             $ids_by_student{$_->[1]}=$_->[0];
 1057:         }
 1058:     }
 1059:     return $ids_by_student{$student} if(exists( $ids_by_student{$student}));
 1060:     return undef; # error
 1061: }
 1062: 
 1063: sub get_student {
 1064:     my ($student_id) = @_;
 1065:     if (! exists($students_by_id{$student_id})  || 
 1066:         ! defined($students_by_id{$student_id}) ||
 1067:         $students_by_id{$student_id} eq '') {
 1068:         my @Result = &Apache::lonmysql::get_rows($student_table);
 1069:         foreach (@Result) {
 1070:             $students_by_id{$_->[0]}=$_->[1];
 1071:         }
 1072:     }
 1073:     return $students_by_id{$student_id} if(exists($students_by_id{$student_id}));
 1074:     return undef; # error
 1075: }
 1076: 
 1077: sub populate_student_table {
 1078:     my ($courseid) = @_;
 1079:     if (! defined($courseid)) {
 1080:         $courseid = $ENV{'request.course.id'};
 1081:     }
 1082:     #
 1083:     &setup_table_names($courseid);
 1084:     my $dbh = &Apache::lonmysql::get_dbh();
 1085:     my $request = 'INSERT IGNORE INTO '.$student_table.
 1086:         "(student,section,status) VALUES ";
 1087:     my $classlist = &get_classlist($courseid);
 1088:     my $student_count=0;
 1089:     while (my ($student,$data) = each %$classlist) {
 1090:         my ($section,$status) = ($data->[&CL_SECTION()],
 1091:                                  $data->[&CL_STATUS()]);
 1092:         if ($section eq '' || $section =~ /^\s*$/) {
 1093:             $section = 'none';
 1094:         }
 1095:         $request .= "('".$student."','".$section."','".$status."'),";
 1096:         $student_count++;
 1097:     }
 1098:     return if ($student_count == 0);
 1099:     chop($request);
 1100:     $dbh->do($request);
 1101:     if ($dbh->err()) {
 1102:         &Apache::lonnet::logthis("error ".$dbh->errstr().
 1103:                                  " occured executing \n".
 1104:                                  $request);
 1105:     }
 1106:     return;
 1107: }
 1108: 
 1109: ################################################
 1110: ################################################
 1111: 
 1112: =pod
 1113: 
 1114: =item &clear_internal_caches()
 1115: 
 1116: Causes the internal caches used in get_student_id, get_student,
 1117: get_symb_id, get_symb, get_part_id, and get_part to be undef'd.
 1118: 
 1119: Needs to be called before the first operation with the MySQL database
 1120: for a given Apache request.
 1121: 
 1122: =cut
 1123: 
 1124: ################################################
 1125: ################################################
 1126: sub clear_internal_caches {
 1127:     $have_read_part_table = 0;
 1128:     undef(%ids_by_part);
 1129:     undef(%parts_by_id);
 1130:     $have_read_symb_table = 0;
 1131:     undef(%ids_by_symb);
 1132:     undef(%symbs_by_id);
 1133:     $have_read_student_table = 0;
 1134:     undef(%ids_by_student);
 1135:     undef(%students_by_id);
 1136: }
 1137: 
 1138: 
 1139: ################################################
 1140: ################################################
 1141: 
 1142: =pod
 1143: 
 1144: =item &update_full_student_data($sname,$sdom,$courseid)
 1145: 
 1146: Does a lonnet::dump on a student to populate the courses tables.
 1147: 
 1148: Input: $sname, $sdom, $courseid
 1149: 
 1150: Output: $returnstatus
 1151: 
 1152: $returnstatus is a string describing any errors that occured.  'okay' is the
 1153: default.
 1154: 
 1155: This subroutine loads a students data using lonnet::dump and inserts
 1156: it into the MySQL database.  The inserts are done on three tables, 
 1157: $fulldump_response_table, $fulldump_part_table, and $fulldump_timestamp_table.
 1158: The INSERT calls are made directly by this subroutine, not through lonmysql 
 1159: because we do a 'bulk'insert which takes advantage of MySQLs non-SQL 
 1160: compliant INSERT command to insert multiple rows at a time.  
 1161: If anything has gone wrong during this process, $returnstatus is updated with 
 1162: a description of the error.
 1163: 
 1164: Once the "fulldump" tables are updated, the tables used for chart and
 1165: spreadsheet (which hold only the current state of the student on their
 1166: homework, not historical data) are updated.  If all updates have occured 
 1167: successfully, $student_table is updated to reflect the time of the update.
 1168: 
 1169: Notice we do not insert the data and immediately query it.  This means it
 1170: is possible for there to be data returned this first time that is not 
 1171: available the second time.  CYA.
 1172: 
 1173: =cut
 1174: 
 1175: ################################################
 1176: ################################################
 1177: sub update_full_student_data {
 1178:     my ($sname,$sdom,$courseid) = @_;
 1179:     #
 1180:     # Set up database names
 1181:     &setup_table_names($courseid);
 1182:     #
 1183:     my $student_id = &get_student_id($sname,$sdom);
 1184:     my $student = $sname.':'.$sdom;
 1185:     #
 1186:     my $returnstatus = 'okay';
 1187:     #
 1188:     # Download students data
 1189:     my $time_of_retrieval = time;
 1190:     my @tmp = &Apache::lonnet::dump($courseid,$sdom,$sname);
 1191:     if (@tmp && $tmp[0] =~ /^error/) {
 1192:         $returnstatus = 'error retrieving full student data';
 1193:         return $returnstatus;
 1194:     } elsif (! @tmp) {
 1195:         $returnstatus = 'okay: no student data';
 1196:         return $returnstatus;
 1197:     }
 1198:     my %studentdata = @tmp;
 1199:     #
 1200:     # Get database handle and clean out the tables 
 1201:     my $dbh = &Apache::lonmysql::get_dbh();
 1202:     $dbh->do('DELETE FROM '.$fulldump_response_table.' WHERE student_id='.
 1203:              $student_id);
 1204:     $dbh->do('DELETE FROM '.$fulldump_part_table.' WHERE student_id='.
 1205:              $student_id);
 1206:     $dbh->do('DELETE FROM '.$fulldump_timestamp_table.' WHERE student_id='.
 1207:              $student_id);
 1208:     #
 1209:     # Parse and store the data into a form we can handle
 1210:     my $partdata;
 1211:     my $respdata;
 1212:     while (my ($key,$value) = each(%studentdata)) {
 1213:         next if ($key =~ /^(\d+):(resource$|subnum$|keys:)/);
 1214:         my ($transaction,$symb,$parameter) = split(':',$key);
 1215:         my $symb_id = &get_symb_id($symb);
 1216:         if ($parameter eq 'timestamp') {
 1217:             # We can deal with 'timestamp' right away
 1218:             my @timestamp_storage = ($symb_id,$student_id,
 1219:                                      $transaction,$value);
 1220:             my $store_command = 'INSERT IGNORE INTO '.$fulldump_timestamp_table.
 1221:                 " VALUES ('".join("','",@timestamp_storage)."');";
 1222:             $dbh->do($store_command);
 1223:             if ($dbh->err()) {
 1224:                 &Apache::lonnet::logthis('unable to execute '.$store_command);
 1225:                 &Apache::lonnet::logthis($dbh->errstr());
 1226:             }
 1227:             next;
 1228:         } elsif ($parameter eq 'version') {
 1229:             next;
 1230:         } elsif ($parameter =~ /^resource\.(.*)\.(tries|
 1231:                                                   award|
 1232:                                                   awarded|
 1233:                                                   previous|
 1234:                                                   solved|
 1235:                                                   awarddetail|
 1236:                                                   submission|
 1237:                                                   submissiongrading|
 1238:                                                   molecule)\s*$/x){
 1239:             # we do not have enough information to store an 
 1240:             # entire row, so we save it up until later.
 1241:             my ($part_and_resp_id,$field) = ($1,$2);
 1242:             my ($part,$part_id,$resp,$resp_id);
 1243:             if ($part_and_resp_id =~ /\./) {
 1244:                 ($part,$resp) = split(/\./,$part_and_resp_id);
 1245:                 $part_id = &get_part_id($part);
 1246:                 $resp_id = &get_part_id($resp);
 1247:             } else {
 1248:                 $part_id = &get_part_id($part_and_resp_id);
 1249:             }
 1250:             # Deal with part specific data
 1251:             if ($field =~ /^(tries|award|awarded|previous)$/) {
 1252:                 $partdata->{$symb_id}->{$part_id}->{$transaction}->{$field}=$value;
 1253:             }
 1254:             # deal with response specific data
 1255:             if (defined($resp_id) &&
 1256:                 $field =~ /^(awarddetail|
 1257:                              submission|
 1258:                              submissiongrading|
 1259:                              molecule)$/x) {
 1260:                 if ($field eq 'submission') {
 1261:                     # We have to be careful with user supplied input.
 1262:                     # most of the time we are okay because it is escaped.
 1263:                     # However, there is one wrinkle: submissions which end in
 1264:                     # and odd number of '\' cause insert errors to occur.  
 1265:                     # Best trap this somehow...
 1266:                     $value = $dbh->quote($value);
 1267:                 }
 1268:                 if ($field eq 'submissiongrading' || 
 1269:                     $field eq 'molecule') {
 1270:                     $respdata->{$symb_id}->{$part_id}->{$resp_id}->{$transaction}->{'response_specific'}=$field;
 1271:                     $respdata->{$symb_id}->{$part_id}->{$resp_id}->{$transaction}->{'response_specific_value'}=$value;
 1272:                 } else {
 1273:                     $respdata->{$symb_id}->{$part_id}->{$resp_id}->{$transaction}->{$field}=$value;
 1274:                 }
 1275:             }
 1276:         }
 1277:     }
 1278:     ##
 1279:     ## Store the part data
 1280:     my $store_command = 'INSERT IGNORE INTO '.$fulldump_part_table.
 1281:         ' VALUES '."\n";
 1282:     my $store_rows = 0;
 1283:     while (my ($symb_id,$hash1) = each (%$partdata)) {
 1284:         while (my ($part_id,$hash2) = each (%$hash1)) {
 1285:             while (my ($transaction,$data) = each (%$hash2)) {
 1286:                 $store_command .= "('".join("','",$symb_id,$part_id,
 1287:                                             $student_id,
 1288:                                             $transaction,
 1289:                                             $data->{'tries'},
 1290:                                             $data->{'award'},
 1291:                                             $data->{'awarded'},
 1292:                                             $data->{'previous'})."'),";
 1293:                 $store_rows++;
 1294:             }
 1295:         }
 1296:     }
 1297:     if ($store_rows) {
 1298:         chop($store_command);
 1299:         $dbh->do($store_command);
 1300:         if ($dbh->err) {
 1301:             $returnstatus = 'error storing part data';
 1302:             &Apache::lonnet::logthis('insert error '.$dbh->errstr());
 1303:             &Apache::lonnet::logthis("While attempting\n".$store_command);
 1304:         }
 1305:     }
 1306:     ##
 1307:     ## Store the response data
 1308:     $store_command = 'INSERT IGNORE INTO '.$fulldump_response_table.
 1309:         ' VALUES '."\n";
 1310:     $store_rows = 0;
 1311:     while (my ($symb_id,$hash1) = each (%$respdata)) {
 1312:         while (my ($part_id,$hash2) = each (%$hash1)) {
 1313:             while (my ($resp_id,$hash3) = each (%$hash2)) {
 1314:                 while (my ($transaction,$data) = each (%$hash3)) {
 1315:                     my $submission = $data->{'submission'};
 1316:                     # We have to be careful with user supplied input.
 1317:                     # most of the time we are okay because it is escaped.
 1318:                     # However, there is one wrinkle: submissions which end in
 1319:                     # and odd number of '\' cause insert errors to occur.  
 1320:                     # Best trap this somehow...
 1321:                     $submission = $dbh->quote($submission);
 1322:                     $store_command .= "('".
 1323:                         join("','",$symb_id,$part_id,
 1324:                              $resp_id,$student_id,
 1325:                              $transaction,
 1326:                              $data->{'awarddetail'},
 1327:                              $data->{'response_specific'},
 1328:                              $data->{'response_specific_value'}).
 1329:                              "',".$submission."),";
 1330:                     $store_rows++;
 1331:                 }
 1332:             }
 1333:         }
 1334:     }
 1335:     if ($store_rows) {
 1336:         chop($store_command);
 1337:         $dbh->do($store_command);
 1338:         if ($dbh->err) {
 1339:             $returnstatus = 'error storing response data';
 1340:             &Apache::lonnet::logthis('insert error '.$dbh->errstr());
 1341:             &Apache::lonnet::logthis("While attempting\n".$store_command);
 1342:         }
 1343:     }
 1344:     ##
 1345:     ## Update the students "current" data in the performance 
 1346:     ## and parameters tables.
 1347:     my ($status,undef) = &store_student_data
 1348:         ($sname,$sdom,$courseid,
 1349:          &Apache::lonnet::convert_dump_to_currentdump(\%studentdata));
 1350:     if ($returnstatus eq 'okay' && $status ne 'okay') {
 1351:         $returnstatus = 'error storing current data:'.$status;
 1352:     } elsif ($status ne 'okay') {
 1353:         $returnstatus .= ' error storing current data:'.$status;
 1354:     }        
 1355:     ##
 1356:     ## Update the students time......
 1357:     if ($returnstatus eq 'okay') {
 1358:         &store_updatetime($student_id,$time_of_retrieval,$time_of_retrieval);
 1359:         if ($dbh->err) {
 1360:             if ($returnstatus eq 'okay') {
 1361:                 $returnstatus = 'error updating student time';
 1362:             } else {
 1363:                 $returnstatus = 'error updating student time';
 1364:             }
 1365:         }
 1366:     }
 1367:     return $returnstatus;
 1368: }
 1369: 
 1370: ################################################
 1371: ################################################
 1372: 
 1373: =pod
 1374: 
 1375: =item &update_student_data()
 1376: 
 1377: Input: $sname, $sdom, $courseid
 1378: 
 1379: Output: $returnstatus, \%student_data
 1380: 
 1381: $returnstatus is a string describing any errors that occured.  'okay' is the
 1382: default.
 1383: \%student_data is the data returned by a call to lonnet::currentdump.
 1384: 
 1385: This subroutine loads a students data using lonnet::currentdump and inserts
 1386: it into the MySQL database.  The inserts are done on two tables, 
 1387: $performance_table and $parameters_table.  $parameters_table holds the data 
 1388: that is not included in $performance_table.  See the description of 
 1389: $performance_table elsewhere in this file.  The INSERT calls are made
 1390: directly by this subroutine, not through lonmysql because we do a 'bulk'
 1391: insert which takes advantage of MySQLs non-SQL compliant INSERT command to 
 1392: insert multiple rows at a time.  If anything has gone wrong during this
 1393: process, $returnstatus is updated with a description of the error and
 1394: \%student_data is returned.  
 1395: 
 1396: Notice we do not insert the data and immediately query it.  This means it
 1397: is possible for there to be data returned this first time that is not 
 1398: available the second time.  CYA.
 1399: 
 1400: =cut
 1401: 
 1402: ################################################
 1403: ################################################
 1404: sub update_student_data {
 1405:     my ($sname,$sdom,$courseid) = @_;
 1406:     #
 1407:     # Set up database names
 1408:     &setup_table_names($courseid);
 1409:     #
 1410:     my $student_id = &get_student_id($sname,$sdom);
 1411:     my $student = $sname.':'.$sdom;
 1412:     #
 1413:     my $returnstatus = 'okay';
 1414:     #
 1415:     # Download students data
 1416:     my $time_of_retrieval = time;
 1417:     my @tmp = &Apache::lonnet::currentdump($courseid,$sdom,$sname);
 1418:     if ((scalar(@tmp) > 0) && ($tmp[0] =~ /^error:/)) {
 1419:         &Apache::lonnet::logthis('error getting data for '.
 1420:                                  $sname.':'.$sdom.' in course '.$courseid.
 1421:                                  ':'.$tmp[0]);
 1422:         $returnstatus = 'error getting data';
 1423:         return ($returnstatus,undef);
 1424:     }
 1425:     if (scalar(@tmp) < 1) {
 1426:         return ('no data',undef);
 1427:     }
 1428:     my %student_data = @tmp;
 1429:     my @Results = &store_student_data($sname,$sdom,$courseid,\%student_data);
 1430:     #
 1431:     # Set the students update time
 1432:     if ($Results[0] eq 'okay') {
 1433:         &store_updatetime($student_id,$time_of_retrieval,$time_of_retrieval);
 1434:     }
 1435:     #
 1436:     return @Results;
 1437: }
 1438: 
 1439: sub store_updatetime {
 1440:     my ($student_id,$updatetime,$fullupdatetime)=@_;
 1441:     my $values = '';
 1442:     if (defined($updatetime)) {
 1443:         $values = 'updatetime='.$updatetime.' ';
 1444:     }
 1445:     if (defined($fullupdatetime)) {
 1446:         if ($values ne '') {
 1447:             $values .= ',';
 1448:         }
 1449:         $values .= 'fullupdatetime='.$fullupdatetime.' ';
 1450:     }
 1451:     return if ($values eq '');
 1452:     my $dbh = &Apache::lonmysql::get_dbh();
 1453:     my $request = 'UPDATE '.$student_table.' SET '.$values.
 1454:         ' WHERE student_id='.$student_id.' LIMIT 1';
 1455:     $dbh->do($request);
 1456: }
 1457: 
 1458: sub store_student_data {
 1459:     my ($sname,$sdom,$courseid,$student_data) = @_;
 1460:     #
 1461:     my $student_id = &get_student_id($sname,$sdom);
 1462:     my $student = $sname.':'.$sdom;
 1463:     #
 1464:     my $returnstatus = 'okay';
 1465:     #
 1466:     # Remove all of the students data from the table
 1467:     my $dbh = &Apache::lonmysql::get_dbh();
 1468:     $dbh->do('DELETE FROM '.$performance_table.' WHERE student_id='.
 1469:              $student_id);
 1470:     $dbh->do('DELETE FROM '.$parameters_table.' WHERE student_id='.
 1471:              $student_id);
 1472:     #
 1473:     # Store away the data
 1474:     #
 1475:     my $starttime = Time::HiRes::time;
 1476:     my $elapsed = 0;
 1477:     my $rows_stored;
 1478:     my $store_parameters_command  = 'INSERT IGNORE INTO '.$parameters_table.
 1479:         ' VALUES '."\n";
 1480:     my $num_parameters = 0;
 1481:     my $store_performance_command = 'INSERT IGNORE INTO '.$performance_table.
 1482:         ' VALUES '."\n";
 1483:     return ('error',undef) if (! defined($dbh));
 1484:     while (my ($current_symb,$param_hash) = each(%{$student_data})) {
 1485:         #
 1486:         # make sure the symb is set up properly
 1487:         my $symb_id = &get_symb_id($current_symb);
 1488:         #
 1489:         # Load data into the tables
 1490:         while (my ($parameter,$value) = each(%$param_hash)) {
 1491:             my $newstring;
 1492:             if ($parameter !~ /(timestamp|resource\.(.*)\.(solved|tries|awarded|award|awarddetail|previous))/) {
 1493:                 $newstring = "('".join("','",
 1494:                                        $symb_id,$student_id,
 1495:                                        $parameter)."',".
 1496:                                            $dbh->quote($value)."),\n";
 1497:                 $num_parameters ++;
 1498:                 if ($newstring !~ /''/) {
 1499:                     $store_parameters_command .= $newstring;
 1500:                     $rows_stored++;
 1501:                 }
 1502:             }
 1503:             next if ($parameter !~ /^resource\.(.*)\.solved$/);
 1504:             #
 1505:             my $part = $1;
 1506:             my $part_id = &get_part_id($part);
 1507:             next if (!defined($part_id));
 1508:             my $solved  = $value;
 1509:             my $tries   = $param_hash->{'resource.'.$part.'.tries'};
 1510:             my $awarded = $param_hash->{'resource.'.$part.'.awarded'};
 1511:             my $award   = $param_hash->{'resource.'.$part.'.award'};
 1512:             my $awarddetail = $param_hash->{'resource.'.$part.'.awarddetail'};
 1513:             my $timestamp = $param_hash->{'timestamp'};
 1514:             #
 1515:             $solved      = '' if (! defined($solved));
 1516:             $tries       = '' if (! defined($tries));
 1517:             $awarded     = '' if (! defined($awarded));
 1518:             $award       = '' if (! defined($award));
 1519:             $awarddetail = '' if (! defined($awarddetail));
 1520:             $newstring = "('".join("','",$symb_id,$student_id,$part_id,$part,
 1521:                                    $solved,$tries,$awarded,$award,
 1522:                                    $awarddetail,$timestamp)."'),\n";
 1523:             $store_performance_command .= $newstring;
 1524:             $rows_stored++;
 1525:         }
 1526:     }
 1527:     chop $store_parameters_command;
 1528:     chop $store_parameters_command;
 1529:     chop $store_performance_command;
 1530:     chop $store_performance_command;
 1531:     my $start = Time::HiRes::time;
 1532:     $dbh->do($store_performance_command);
 1533:     if ($dbh->err()) {
 1534:         &Apache::lonnet::logthis(' bigass insert error:'.$dbh->errstr());
 1535:         &Apache::lonnet::logthis('command = '.$store_performance_command);
 1536:         $returnstatus = 'error: unable to insert performance into database';
 1537:         return ($returnstatus,$student_data);
 1538:     }
 1539:     $dbh->do($store_parameters_command) if ($num_parameters>0);
 1540:     if ($dbh->err()) {
 1541:         &Apache::lonnet::logthis(' bigass insert error:'.$dbh->errstr());
 1542:         &Apache::lonnet::logthis('command = '.$store_parameters_command);
 1543:         &Apache::lonnet::logthis('rows_stored = '.$rows_stored);
 1544:         &Apache::lonnet::logthis('student_id = '.$student_id);
 1545:         $returnstatus = 'error: unable to insert parameters into database';
 1546:         return ($returnstatus,$student_data);
 1547:     }
 1548:     $elapsed += Time::HiRes::time - $start;
 1549:     return ($returnstatus,$student_data);
 1550: }
 1551: 
 1552: ######################################
 1553: ######################################
 1554: 
 1555: =pod
 1556: 
 1557: =item &ensure_tables_are_set_up($courseid)
 1558: 
 1559: Checks to be sure the MySQL tables for the given class are set up.
 1560: If $courseid is omitted it will be obtained from the environment.
 1561: 
 1562: Returns nothing on success and 'error' on failure
 1563: 
 1564: =cut
 1565: 
 1566: ######################################
 1567: ######################################
 1568: sub ensure_tables_are_set_up {
 1569:     my ($courseid) = @_;
 1570:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
 1571:     # 
 1572:     # Clean out package variables
 1573:     &setup_table_names($courseid);
 1574:     #
 1575:     # if the tables do not exist, make them
 1576:     my @CurrentTable = &Apache::lonmysql::tables_in_db();
 1577:     my ($found_symb,$found_student,$found_part,
 1578:         $found_performance,$found_parameters,$found_fulldump_part,
 1579:         $found_fulldump_response,$found_fulldump_timestamp,
 1580:         $found_weight);
 1581:     foreach (@CurrentTable) {
 1582:         $found_symb        = 1 if ($_ eq $symb_table);
 1583:         $found_student     = 1 if ($_ eq $student_table);
 1584:         $found_part        = 1 if ($_ eq $part_table);
 1585:         $found_performance = 1 if ($_ eq $performance_table);
 1586:         $found_parameters  = 1 if ($_ eq $parameters_table);
 1587:         $found_fulldump_part      = 1 if ($_ eq $fulldump_part_table);
 1588:         $found_fulldump_response  = 1 if ($_ eq $fulldump_response_table);
 1589:         $found_fulldump_timestamp = 1 if ($_ eq $fulldump_timestamp_table);
 1590:         $found_weight      = 1 if ($_ eq $weight_table);
 1591:     }
 1592:     if (!$found_symb          || 
 1593:         !$found_student       || !$found_part              ||
 1594:         !$found_performance   || !$found_parameters        ||
 1595:         !$found_fulldump_part || !$found_fulldump_response ||
 1596:         !$found_fulldump_timestamp || !$found_weight ) {
 1597:         if (&init_dbs($courseid)) {
 1598:             return 'error';
 1599:         }
 1600:     }
 1601: }
 1602: 
 1603: ################################################
 1604: ################################################
 1605: 
 1606: =pod
 1607: 
 1608: =item &ensure_current_data()
 1609: 
 1610: Input: $sname, $sdom, $courseid
 1611: 
 1612: Output: $status, $data
 1613: 
 1614: This routine ensures the data for a given student is up to date.
 1615: The $student_table is queried to determine the time of the last update.  
 1616: If the students data is out of date, &update_student_data() is called.  
 1617: The return values from the call to &update_student_data() are returned.
 1618: 
 1619: =cut
 1620: 
 1621: ################################################
 1622: ################################################
 1623: sub ensure_current_data {
 1624:     my ($sname,$sdom,$courseid) = @_;
 1625:     my $status = 'okay';   # return value
 1626:     #
 1627:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
 1628:     &ensure_tables_are_set_up($courseid);
 1629:     #
 1630:     # Get the update time for the user
 1631:     my $updatetime = 0;
 1632:     my $modifiedtime = &Apache::lonnet::GetFileTimestamp
 1633:         ($sdom,$sname,$courseid.'.db',
 1634:          $Apache::lonnet::perlvar{'lonUsersDir'});
 1635:     #
 1636:     my $student_id = &get_student_id($sname,$sdom);
 1637:     my @Result = &Apache::lonmysql::get_rows($student_table,
 1638:                                              "student_id ='$student_id'");
 1639:     my $data = undef;
 1640:     if (@Result) {
 1641:         $updatetime = $Result[0]->[5];  # Ack!  This is dumb!
 1642:     }
 1643:     if ($modifiedtime > $updatetime) {
 1644:         ($status,$data) = &update_student_data($sname,$sdom,$courseid);
 1645:     }
 1646:     return ($status,$data);
 1647: }
 1648: 
 1649: ################################################
 1650: ################################################
 1651: 
 1652: =pod
 1653: 
 1654: =item &ensure_current_full_data($sname,$sdom,$courseid)
 1655: 
 1656: Input: $sname, $sdom, $courseid
 1657: 
 1658: Output: $status
 1659: 
 1660: This routine ensures the fulldata (the data from a lonnet::dump, not a
 1661: lonnet::currentdump) for a given student is up to date.
 1662: The $student_table is queried to determine the time of the last update.  
 1663: If the students fulldata is out of date, &update_full_student_data() is
 1664: called.  
 1665: 
 1666: The return value from the call to &update_full_student_data() is returned.
 1667: 
 1668: =cut
 1669: 
 1670: ################################################
 1671: ################################################
 1672: sub ensure_current_full_data {
 1673:     my ($sname,$sdom,$courseid) = @_;
 1674:     my $status = 'okay';   # return value
 1675:     #
 1676:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
 1677:     &ensure_tables_are_set_up($courseid);
 1678:     #
 1679:     # Get the update time for the user
 1680:     my $modifiedtime = &Apache::lonnet::GetFileTimestamp
 1681:         ($sdom,$sname,$courseid.'.db',
 1682:          $Apache::lonnet::perlvar{'lonUsersDir'});
 1683:     #
 1684:     my $student_id = &get_student_id($sname,$sdom);
 1685:     my @Result = &Apache::lonmysql::get_rows($student_table,
 1686:                                              "student_id ='$student_id'");
 1687:     my $updatetime;
 1688:     if (@Result && ref($Result[0]) eq 'ARRAY') {
 1689:         $updatetime = $Result[0]->[6];
 1690:     }
 1691:     if (! defined($updatetime) || $modifiedtime > $updatetime) {
 1692:         $status = &update_full_student_data($sname,$sdom,$courseid);
 1693:     }
 1694:     return $status;
 1695: }
 1696: 
 1697: ################################################
 1698: ################################################
 1699: 
 1700: =pod
 1701: 
 1702: =item &get_student_data_from_performance_cache()
 1703: 
 1704: Input: $sname, $sdom, $symb, $courseid
 1705: 
 1706: Output: hash reference containing the data for the given student.
 1707: If $symb is undef, all the students data is returned.
 1708: 
 1709: This routine is the heart of the local caching system.  See the description
 1710: of $performance_table, $symb_table, $student_table, and $part_table.  The
 1711: main task is building the MySQL request.  The tables appear in the request
 1712: in the order in which they should be parsed by MySQL.  When searching
 1713: on a student the $student_table is used to locate the 'student_id'.  All
 1714: rows in $performance_table which have a matching 'student_id' are returned,
 1715: with data from $part_table and $symb_table which match the entries in
 1716: $performance_table, 'part_id' and 'symb_id'.  When searching on a symb,
 1717: the $symb_table is processed first, with matching rows grabbed from 
 1718: $performance_table and filled in from $part_table and $student_table in
 1719: that order.  
 1720: 
 1721: Running 'EXPLAIN ' on the 'SELECT' statements generated can be quite 
 1722: interesting, especially if you play with the order the tables are listed.  
 1723: 
 1724: =cut
 1725: 
 1726: ################################################
 1727: ################################################
 1728: sub get_student_data_from_performance_cache {
 1729:     my ($sname,$sdom,$symb,$courseid)=@_;
 1730:     my $student = $sname.':'.$sdom if (defined($sname) && defined($sdom));
 1731:     &setup_table_names($courseid);
 1732:     #
 1733:     # Return hash
 1734:     my $studentdata;
 1735:     #
 1736:     my $dbh = &Apache::lonmysql::get_dbh();
 1737:     my $request = "SELECT ".
 1738:         "d.symb,a.part,a.solved,a.tries,a.awarded,a.award,a.awarddetail,".
 1739:             "a.timestamp ";
 1740:     if (defined($student)) {
 1741:         $request .= "FROM $student_table AS b ".
 1742:             "LEFT JOIN $performance_table AS a ON b.student_id=a.student_id ".
 1743: #            "LEFT JOIN $part_table AS c ON c.part_id = a.part_id ".
 1744:             "LEFT JOIN $symb_table AS d ON d.symb_id = a.symb_id ".
 1745:                 "WHERE student='$student'";
 1746:         if (defined($symb) && $symb ne '') {
 1747:             $request .= " AND d.symb=".$dbh->quote($symb);
 1748:         }
 1749:     } elsif (defined($symb) && $symb ne '') {
 1750:         $request .= "FROM $symb_table as d ".
 1751:             "LEFT JOIN $performance_table AS a ON d.symb_id=a.symb_id ".
 1752: #            "LEFT JOIN $part_table    AS c ON c.part_id = a.part_id ".
 1753:             "LEFT JOIN $student_table AS b ON b.student_id = a.student_id ".
 1754:                 "WHERE symb='".$dbh->quote($symb)."'";
 1755:     }
 1756:     my $starttime = Time::HiRes::time;
 1757:     my $rows_retrieved = 0;
 1758:     my $sth = $dbh->prepare($request);
 1759:     $sth->execute();
 1760:     if ($sth->err()) {
 1761:         &Apache::lonnet::logthis("Unable to execute MySQL request:");
 1762:         &Apache::lonnet::logthis("\n".$request."\n");
 1763:         &Apache::lonnet::logthis("error is:".$sth->errstr());
 1764:         return undef;
 1765:     }
 1766:     foreach my $row (@{$sth->fetchall_arrayref}) {
 1767:         $rows_retrieved++;
 1768:         my ($symb,$part,$solved,$tries,$awarded,$award,$awarddetail,$time) = 
 1769:             (@$row);
 1770:         my $base = 'resource.'.$part;
 1771:         $studentdata->{$symb}->{$base.'.solved'}  = $solved;
 1772:         $studentdata->{$symb}->{$base.'.tries'}   = $tries;
 1773:         $studentdata->{$symb}->{$base.'.awarded'} = $awarded;
 1774:         $studentdata->{$symb}->{$base.'.award'}   = $award;
 1775:         $studentdata->{$symb}->{$base.'.awarddetail'} = $awarddetail;
 1776:         $studentdata->{$symb}->{'timestamp'} = $time if (defined($time) && $time ne '');
 1777:     }
 1778:     ## Get misc parameters
 1779:     $request = 'SELECT c.symb,a.parameter,a.value '.
 1780:         "FROM $student_table AS b ".
 1781:         "LEFT JOIN $parameters_table AS a ON b.student_id=a.student_id ".
 1782:         "LEFT JOIN $symb_table AS c ON c.symb_id = a.symb_id ".
 1783:         "WHERE student='$student'";
 1784:     if (defined($symb) && $symb ne '') {
 1785:         $request .= " AND c.symb=".$dbh->quote($symb);
 1786:     }
 1787:     $sth = $dbh->prepare($request);
 1788:     $sth->execute();
 1789:     if ($sth->err()) {
 1790:         &Apache::lonnet::logthis("Unable to execute MySQL request:");
 1791:         &Apache::lonnet::logthis("\n".$request."\n");
 1792:         &Apache::lonnet::logthis("error is:".$sth->errstr());
 1793:         if (defined($symb) && $symb ne '') {
 1794:             $studentdata = $studentdata->{$symb};
 1795:         }
 1796:         return $studentdata;
 1797:     }
 1798:     #
 1799:     foreach my $row (@{$sth->fetchall_arrayref}) {
 1800:         $rows_retrieved++;
 1801:         my ($symb,$parameter,$value) = (@$row);
 1802:         $studentdata->{$symb}->{$parameter}  = $value;
 1803:     }
 1804:     #
 1805:     if (defined($symb) && $symb ne '') {
 1806:         $studentdata = $studentdata->{$symb};
 1807:     }
 1808:     return $studentdata;
 1809: }
 1810: 
 1811: ################################################
 1812: ################################################
 1813: 
 1814: =pod
 1815: 
 1816: =item &get_current_state()
 1817: 
 1818: Input: $sname,$sdom,$symb,$courseid
 1819: 
 1820: Output: Described below
 1821: 
 1822: Retrieve the current status of a students performance.  $sname and
 1823: $sdom are the only required parameters.  If $symb is undef the results
 1824: of an &Apache::lonnet::currentdump() will be returned.  
 1825: If $courseid is undef it will be retrieved from the environment.
 1826: 
 1827: The return structure is based on &Apache::lonnet::currentdump.  If
 1828: $symb is unspecified, all the students data is returned in a hash of
 1829: the form:
 1830: ( 
 1831:   symb1 => { param1 => value1, param2 => value2 ... },
 1832:   symb2 => { param1 => value1, param2 => value2 ... },
 1833: )
 1834: 
 1835: If $symb is specified, a hash of 
 1836: (
 1837:   param1 => value1, 
 1838:   param2 => value2,
 1839: )
 1840: is returned.
 1841: 
 1842: If no data is found for $symb, or if the student has no performance data,
 1843: an empty list is returned.
 1844: 
 1845: =cut
 1846: 
 1847: ################################################
 1848: ################################################
 1849: sub get_current_state {
 1850:     my ($sname,$sdom,$symb,$courseid,$forcedownload)=@_;
 1851:     #
 1852:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
 1853:     #
 1854:     return () if (! defined($sname) || ! defined($sdom));
 1855:     #
 1856:     my ($status,$data) = &ensure_current_data($sname,$sdom,$courseid);
 1857: #    &Apache::lonnet::logthis
 1858: #        ('sname = '.$sname.
 1859: #         ' domain = '.$sdom.
 1860: #         ' status = '.$status.
 1861: #         ' data is '.(defined($data)?'defined':'undefined'));
 1862: #    while (my ($symb,$hash) = each(%$data)) {
 1863: #        &Apache::lonnet::logthis($symb."\n----------------------------------");
 1864: #        while (my ($key,$value) = each (%$hash)) {
 1865: #            &Apache::lonnet::logthis("   ".$key." = ".$value);
 1866: #        }
 1867: #    }
 1868:     #
 1869:     if (defined($data) && defined($symb) && ref($data->{$symb})) {
 1870:         return %{$data->{$symb}};
 1871:     } elsif (defined($data) && ! defined($symb) && ref($data)) {
 1872:         return %$data;
 1873:     } 
 1874:     if ($status eq 'no data') {
 1875:         return ();
 1876:     } else {
 1877:         if ($status ne 'okay' && $status ne '') {
 1878:             &Apache::lonnet::logthis('status = '.$status);
 1879:             return ();
 1880:         }
 1881:         my $returnhash = &get_student_data_from_performance_cache($sname,$sdom,
 1882:                                                       $symb,$courseid);
 1883:         return %$returnhash if (defined($returnhash));
 1884:     }
 1885:     return ();
 1886: }
 1887: 
 1888: ################################################
 1889: ################################################
 1890: 
 1891: =pod
 1892: 
 1893: =item &get_problem_statistics()
 1894: 
 1895: Gather data on a given problem.  The database is assumed to be 
 1896: populated and all local caching variables are assumed to be set
 1897: properly.  This means you need to call &ensure_current_data for
 1898: the students you are concerned with prior to calling this routine.
 1899: 
 1900: Inputs: $Sections, $status, $symb, $part, $courseid, $starttime, $endtime
 1901: 
 1902: =over 4
 1903: 
 1904: =item $Sections Array ref containing section names for students.  
 1905: 'all' is allowed to be the first (and only) item in the array.
 1906: 
 1907: =item $status String describing the status of students
 1908: 
 1909: =item $symb is the symb for the problem.
 1910: 
 1911: =item $part is the part id you need statistics for
 1912: 
 1913: =item $courseid is the course id, of course!
 1914: 
 1915: =item $starttime and $endtime are unix times which to use to limit
 1916: the statistical data.
 1917: 
 1918: =back
 1919: 
 1920: Outputs: See the code for up to date information.  A hash reference is
 1921: returned.  The hash has the following keys defined:
 1922: 
 1923: =over 4
 1924: 
 1925: =item num_students The number of students attempting the problem
 1926:       
 1927: =item tries The total number of tries for the students
 1928:       
 1929: =item max_tries The maximum number of tries taken
 1930:       
 1931: =item mean_tries The average number of tries
 1932:       
 1933: =item num_solved The number of students able to solve the problem
 1934:       
 1935: =item num_override The number of students whose answer is 'correct_by_override'
 1936:       
 1937: =item deg_of_diff The degree of difficulty of the problem
 1938:       
 1939: =item std_tries The standard deviation of the number of tries
 1940:       
 1941: =item skew_tries The skew of the number of tries
 1942: 
 1943: =item per_wrong The number of students attempting the problem who were not
 1944: able to answer it correctly.
 1945: 
 1946: =back
 1947: 
 1948: =cut
 1949: 
 1950: ################################################
 1951: ################################################
 1952: sub get_problem_statistics {
 1953:     my ($Sections,$status,$symb,$part,$courseid,$starttime,$endtime) = @_;
 1954:     return if (! defined($symb) || ! defined($part));
 1955:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
 1956:     #
 1957:     &setup_table_names($courseid);
 1958:     my $symb_id = &get_symb_id($symb);
 1959:     my $part_id = &get_part_id($part);
 1960:     my $stats_table = $courseid.'_problem_stats';
 1961:     #
 1962:     my $dbh = &Apache::lonmysql::get_dbh();
 1963:     return undef if (! defined($dbh));
 1964:     #
 1965:     # Clean out the table
 1966:     $dbh->do('DROP TABLE '.$stats_table);  # May return an error
 1967:     my $request = 
 1968:         'CREATE TEMPORARY TABLE '.$stats_table.' '.
 1969:         'SELECT a.student_id,a.solved,a.award,a.awarded,a.tries '.
 1970:         'FROM '.$performance_table.' AS a ';
 1971:     #
 1972:     # See if we need to include some requirements on the students
 1973:     if ((defined($Sections) && lc($Sections->[0]) ne 'all') || 
 1974:         (defined($status)   && lc($status)        ne 'any')) {
 1975:         $request .= 'NATURAL LEFT JOIN '.$student_table.' AS b ';
 1976:     }
 1977:     $request .= ' WHERE a.symb_id='.$symb_id.' AND a.part_id='.$part_id;
 1978:     #
 1979:     # Limit the students included to those specified
 1980:     if (defined($Sections) && lc($Sections->[0]) ne 'all') {
 1981:         $request .= ' AND ('.
 1982:             join(' OR ', map { "b.section='".$_."'" } @$Sections
 1983:                  ).')';
 1984:     }
 1985:     if (defined($status) && lc($status) ne 'any') {
 1986:         $request .= " AND b.status='".$status."'";
 1987:     }
 1988:     #
 1989:     # Limit by starttime and endtime
 1990:     my $time_requirements = undef;
 1991:     if (defined($starttime)) {
 1992:         $time_requirements .= 'a.timestamp>='.$starttime;
 1993:         if (defined($endtime)) {
 1994:             $time_requirements .= ' AND a.timestamp<='.$endtime;
 1995:         }
 1996:     } elsif (defined($endtime)) {
 1997:         $time_requirements .= 'a.timestamp<='.$endtime;
 1998:     }
 1999:     if (defined($time_requirements)) {
 2000:         $request .= ' AND '.$time_requirements;
 2001:     }
 2002:     #
 2003:     # Finally, execute the request to create the temporary table
 2004:     $dbh->do($request);
 2005:     #
 2006:     # Collect the first suite of statistics
 2007:     $request = 'SELECT COUNT(*),SUM(tries),'.
 2008:         'AVG(tries),STD(tries) '.
 2009:         'FROM '.$stats_table;
 2010:     my ($num,$tries,$mean,$STD) = &execute_SQL_request
 2011:         ($dbh,$request);
 2012:     #
 2013:     $request = 'SELECT MAX(tries),MIN(tries) FROM '.$stats_table.
 2014:         ' WHERE awarded>0';
 2015:     if (defined($time_requirements)) {
 2016:         $request .= ' AND '.$time_requirements;
 2017:     }
 2018:     my ($max,$min) = &execute_SQL_request($dbh,$request);
 2019:     #
 2020:     $request = 'SELECT SUM(awarded) FROM '.$stats_table;
 2021:     if (defined($time_requirements)) {
 2022:         $request .= ' AND '.$time_requirements;
 2023:     }
 2024:     my ($Solved) = &execute_SQL_request($dbh,$request);
 2025:     #
 2026:     $request = 'SELECT SUM(awarded) FROM '.$stats_table.
 2027:         " WHERE solved='correct_by_override'";
 2028:     if (defined($time_requirements)) {
 2029:         $request .= ' AND '.$time_requirements;
 2030:     }
 2031:     my ($solved) = &execute_SQL_request($dbh,$request);
 2032:     #
 2033:     $num    = 0 if (! defined($num));
 2034:     $tries  = 0 if (! defined($tries));
 2035:     $max    = 0 if (! defined($max));
 2036:     $min    = 0 if (! defined($min));
 2037:     $STD    = 0 if (! defined($STD));
 2038:     $Solved = 0 if (! defined($Solved));
 2039:     $solved = 0 if (! defined($solved));
 2040:     #
 2041:     # Compute the more complicated statistics
 2042:     my $DegOfDiff = 'nan';
 2043:     $DegOfDiff = 1-($Solved)/$tries if ($tries>0);
 2044:     #
 2045:     my $SKEW = 'nan';
 2046:     my $wrongpercent = 0;
 2047:     my $numwrong = 'nan';
 2048:     if ($num > 0) {
 2049:         ($SKEW) = &execute_SQL_request($dbh,'SELECT SQRT(SUM('.
 2050:                                      'POWER(tries - '.$STD.',3)'.
 2051:                                      '))/'.$num.' FROM '.$stats_table);
 2052:         $numwrong = $num-$Solved;
 2053:         $wrongpercent=int(10*100*$numwrong/$num)/10;
 2054:     }
 2055:     #
 2056:     # Drop the temporary table
 2057:     $dbh->do('DROP TABLE '.$stats_table);  # May return an error
 2058:     #
 2059:     # Return result
 2060:     return { num_students => $num,
 2061:              tries        => $tries,
 2062:              max_tries    => $max,
 2063:              min_tries    => $min,
 2064:              mean_tries   => $mean,
 2065:              std_tries    => $STD,
 2066:              skew_tries   => $SKEW,
 2067:              num_solved   => $Solved,
 2068:              num_override => $solved,
 2069:              num_wrong    => $numwrong,
 2070:              per_wrong    => $wrongpercent,
 2071:              deg_of_diff  => $DegOfDiff };
 2072: }
 2073: 
 2074: ##
 2075: ## This is a helper for get_statistics
 2076: sub execute_SQL_request {
 2077:     my ($dbh,$request)=@_;
 2078: #    &Apache::lonnet::logthis($request);
 2079:     my $sth = $dbh->prepare($request);
 2080:     $sth->execute();
 2081:     my $row = $sth->fetchrow_arrayref();
 2082:     if (ref($row) eq 'ARRAY' && scalar(@$row)>0) {
 2083:         return @$row;
 2084:     }
 2085:     return ();
 2086: }
 2087: 
 2088: ######################################################
 2089: ######################################################
 2090: 
 2091: =pod
 2092: 
 2093: =item &populate_weight_table
 2094: 
 2095: =cut
 2096: 
 2097: ######################################################
 2098: ######################################################
 2099: sub populate_weight_table {
 2100:     my ($courseid) = @_;
 2101:     if (! defined($courseid)) {
 2102:         $courseid = $ENV{'request.course.id'};
 2103:     }
 2104:     #
 2105:     &setup_table_names($courseid);
 2106:     my ($top,$sequences,$assessments) = get_sequence_assessment_data();
 2107:     if (! defined($top) || ! ref($top)) {
 2108:         # There has been an error, better report it
 2109:         &Apache::lonnet::logthis('top is undefined');
 2110:         return;
 2111:     }
 2112:     #       Since we use lonnet::EXT to retrieve problem weights,
 2113:     #       to ensure current data we must clear the caches out.
 2114:     &Apache::lonnet::clear_EXT_cache_status();
 2115:     my $dbh = &Apache::lonmysql::get_dbh();
 2116:     my $request = 'INSERT IGNORE INTO '.$weight_table.
 2117:         "(symb_id,part_id,weight) VALUES ";
 2118:     my $weight;
 2119:     foreach my $res (@$assessments) {
 2120:         my $symb_id = &get_symb_id($res->{'symb'});
 2121:         foreach my $part (@{$res->{'parts'}}) {
 2122:             my $part_id = &get_part_id($part);
 2123:             $weight = &Apache::lonnet::EXT('resource.'.$part.'.weight',
 2124:                                            $res->{'symb'},
 2125:                                            undef,undef,undef);
 2126:             if (!defined($weight) || ($weight eq '')) { 
 2127:                 $weight=1;
 2128:             }
 2129:             $request .= "('".$symb_id."','".$part_id."','".$weight."'),";
 2130:         }
 2131:     }
 2132:     $request =~ s/(,)$//;
 2133: #    &Apache::lonnet::logthis('request = '.$/.$request);
 2134:     $dbh->do($request);
 2135:     if ($dbh->err()) {
 2136:         &Apache::lonnet::logthis("error ".$dbh->errstr().
 2137:                                  " occured executing \n".
 2138:                                  $request);
 2139:     }
 2140:     return;
 2141: }
 2142: 
 2143: ##########################################################
 2144: ##########################################################
 2145: 
 2146: =pod
 2147: 
 2148: =item &limit_by_start_end_times
 2149: 
 2150: Build SQL WHERE condition which limits the data collected by the start
 2151: and end times provided
 2152: 
 2153: Inputs: $starttime, $endtime, $table
 2154: 
 2155: Returns: $time_limits
 2156: 
 2157: =cut
 2158: 
 2159: ##########################################################
 2160: ##########################################################
 2161: sub limit_by_start_end_time {
 2162:     my ($starttime,$endtime,$table) = @_;
 2163:     my $time_requirements = undef;
 2164:     if (defined($starttime)) {
 2165:         $time_requirements .= $table.".timestamp>='".$starttime."'";
 2166:         if (defined($endtime)) {
 2167:             $time_requirements .= " AND ".$table.".timestamp<='".$endtime."'";
 2168:         }
 2169:     } elsif (defined($endtime)) {
 2170:         $time_requirements .= $table.".timestamp<='".$endtime."'";
 2171:     }
 2172:     return $time_requirements;
 2173: }
 2174: 
 2175: ##########################################################
 2176: ##########################################################
 2177: 
 2178: =pod
 2179: 
 2180: =item &limit_by_section_and_status
 2181: 
 2182: Build SQL WHERE condition which limits the data collected by section and
 2183: student status.
 2184: 
 2185: Inputs: $Sections (array ref)
 2186:     $enrollment (string: 'any', 'expired', 'active')
 2187:     $tablename The name of the table that holds the student data
 2188: 
 2189: Returns: $student_requirements,$enrollment_requirements
 2190: 
 2191: =cut
 2192: 
 2193: ##########################################################
 2194: ##########################################################
 2195: sub limit_by_section_and_status {
 2196:     my ($Sections,$enrollment,$tablename) = @_;
 2197:     my $student_requirements = undef;
 2198:     if ( (defined($Sections) && $Sections->[0] ne 'all')) {
 2199:         $student_requirements = '('.
 2200:             join(' OR ', map { $tablename.".section='".$_."'" } @$Sections
 2201:                  ).')';
 2202:     }
 2203:     #
 2204:     my $enrollment_requirements=undef;
 2205:     if (defined($enrollment) && $enrollment ne 'Any') {
 2206:         $enrollment_requirements = $tablename.".status='".$enrollment."'";
 2207:     }
 2208:     return ($student_requirements,$enrollment_requirements);
 2209: }
 2210: 
 2211: ######################################################
 2212: ######################################################
 2213: 
 2214: =pod
 2215: 
 2216: =item rank_students_by_scores_on_resources
 2217: 
 2218: Inputs: 
 2219:     $resources: array ref of hash ref.  Each hash ref needs key 'symb'.
 2220:     $Sections: array ref of sections to include,
 2221:     $enrollment: string,
 2222:     $courseid (may be omitted)
 2223: 
 2224: Returns; An array of arrays.  The sub arrays contain a student name and
 2225: their score on the resources.
 2226: 
 2227: =cut
 2228: 
 2229: ######################################################
 2230: ######################################################
 2231: sub RNK_student { return 0; };
 2232: sub RNK_score   { return 1; };
 2233: 
 2234: sub rank_students_by_scores_on_resources {
 2235:     my ($resources,$Sections,$enrollment,$courseid,$starttime,$endtime) = @_;
 2236:     return if (! defined($resources) || ! ref($resources) eq 'ARRAY');
 2237:     if (! defined($courseid)) {
 2238:         $courseid = $ENV{'request.course.id'};
 2239:     }
 2240:     #
 2241:     &setup_table_names($courseid);
 2242:     my $dbh = &Apache::lonmysql::get_dbh();
 2243:     my ($section_limits,$enrollment_limits)=
 2244:         &limit_by_section_and_status($Sections,$enrollment,'b');
 2245:     my $symb_limits = '('.join(' OR ',map {'a.symb_id='.&get_symb_id($_);
 2246:                                        } @$resources
 2247:                                ).')';
 2248:     my $time_limits = &limit_by_start_end_time($starttime,$endtime,'a');
 2249:     my $request = 'SELECT b.student,SUM(a.awarded*w.weight) AS score FROM '.
 2250:         $performance_table.' AS a '.
 2251:         'NATURAL LEFT JOIN '.$weight_table.' AS w '.
 2252:         'LEFT JOIN '.$student_table.' AS b ON a.student_id=b.student_id '.
 2253:         'WHERE ';
 2254:     if (defined($section_limits)) {
 2255:         $request .= $section_limits.' AND ';
 2256:     }
 2257:     if (defined($enrollment_limits)) {
 2258:         $request .= $enrollment_limits.' AND ';
 2259:     }
 2260:     if (defined($time_limits)) {
 2261:         $request .= $time_limits.' AND ';
 2262:     }
 2263:     if ($symb_limits ne '()') {
 2264:         $request .= $symb_limits.' AND ';
 2265:     }
 2266:     $request =~ s/( AND )$//;   # Remove extra conjunction
 2267:     $request =~ s/( WHERE )$//; # In case there were no limits placed on it
 2268:     $request .= ' GROUP BY a.student_id ORDER BY score';
 2269:     #&Apache::lonnet::logthis('request = '.$/.$request);
 2270:     my $sth = $dbh->prepare($request);
 2271:     $sth->execute();
 2272:     my $rows = $sth->fetchall_arrayref();
 2273:     return ($rows);
 2274: }
 2275: 
 2276: ########################################################
 2277: ########################################################
 2278: 
 2279: =pod
 2280: 
 2281: =item &get_sum_of_scores
 2282: 
 2283: Inputs: $resource (hash ref, needs {'symb'} key),
 2284: $part, (the part id),
 2285: $students (array ref, contents of array are scalars holding 'sname:sdom'),
 2286: $courseid
 2287: 
 2288: Returns: the sum of the score on the problem part over the students and the
 2289:    maximum possible value for the sum (taken from the weight table).
 2290: 
 2291: =cut
 2292: 
 2293: ########################################################
 2294: ########################################################
 2295: sub get_sum_of_scores {
 2296:     my ($resource,$part,$students,$courseid,$starttime,$endtime) = @_;
 2297:     if (! defined($courseid)) {
 2298:         $courseid = $ENV{'request.course.id'};
 2299:     }
 2300:     #
 2301:     &setup_table_names($courseid);
 2302:     my $dbh = &Apache::lonmysql::get_dbh();
 2303:     my $time_limits = &limit_by_start_end_time($starttime,$endtime,'a');
 2304:     my $request = 'SELECT SUM(a.awarded*w.weight),SUM(w.weight) FROM '.
 2305:         $performance_table.' AS a '.
 2306:         'NATURAL LEFT JOIN '.$weight_table.' AS w ';
 2307:     $request .= 'WHERE a.symb_id='.&get_symb_id($resource->{'symb'}).
 2308:         ' AND a.part_id='.&get_part_id($part);
 2309:     if (defined($time_limits)) {
 2310:         $request .= ' AND '.$time_limits;
 2311:     }
 2312:     if (defined($students)) {
 2313:         $request .= ' AND ('.
 2314:             join(' OR ',map {'a.student_id='.&get_student_id(split(':',$_));
 2315:                          } @$students).
 2316:                              ')';
 2317:     }
 2318:     my $sth = $dbh->prepare($request);
 2319:     $sth->execute();
 2320:     my $rows = $sth->fetchrow_arrayref();
 2321:     if ($dbh->err) {
 2322:         &Apache::lonnet::logthis('error = '.$dbh->errstr());
 2323:         return (undef,undef);
 2324:     }
 2325:     return ($rows->[0],$rows->[1]);
 2326: }
 2327: 
 2328: ########################################################
 2329: ########################################################
 2330: 
 2331: =pod
 2332: 
 2333: =item &score_stats
 2334: 
 2335: Inputs: $Sections, $enrollment, $symbs, $starttime,
 2336:         $endtime, $courseid
 2337: 
 2338: $Sections, $enrollment, $starttime, $endtime, and $courseid are the same as 
 2339: elsewhere in this module.  
 2340: $symbs is an array ref of symbs
 2341: 
 2342: Returns: minimum, maximum, mean, s.d., number of students, and maximum
 2343:   possible of student scores on the given resources
 2344: 
 2345: =cut
 2346: 
 2347: ########################################################
 2348: ########################################################
 2349: sub score_stats {
 2350:     my ($Sections,$enrollment,$symbs,$starttime,$endtime,$courseid)=@_;
 2351:     if (! defined($courseid)) {
 2352:         $courseid = $ENV{'request.course.id'};
 2353:     }
 2354:     #
 2355:     &setup_table_names($courseid);
 2356:     my $dbh = &Apache::lonmysql::get_dbh();
 2357:     #
 2358:     my ($section_limits,$enrollment_limits)=
 2359:         &limit_by_section_and_status($Sections,$enrollment,'b');
 2360:     my $time_limits = &limit_by_start_end_time($starttime,$endtime,'a');
 2361:     my @Symbids = map { &get_symb_id($_); } @{$symbs};
 2362:     #
 2363:     my $stats_table = $courseid.'_problem_stats';
 2364:     my $symb_restriction = join(' OR ',map {'a.symb_id='.$_;} @Symbids);
 2365:     my $request = 'DROP TABLE '.$stats_table;
 2366:     $dbh->do($request);
 2367:     $request = 
 2368:         'CREATE TEMPORARY TABLE '.$stats_table.' '.
 2369:         'SELECT a.student_id,'.
 2370:         'SUM(a.awarded*w.weight) AS score FROM '.
 2371:         $performance_table.' AS a '.
 2372:         'NATURAL LEFT JOIN '.$weight_table.' AS w '.
 2373:         'LEFT JOIN '.$student_table.' AS b ON a.student_id=b.student_id '.
 2374:         'WHERE ('.$symb_restriction.')';
 2375:     if ($time_limits) {
 2376:         $request .= ' AND '.$time_limits;
 2377:     }
 2378:     if ($section_limits) {
 2379:         $request .= ' AND '.$section_limits;
 2380:     }
 2381:     if ($enrollment_limits) {
 2382:         $request .= ' AND '.$enrollment_limits;
 2383:     }
 2384:     $request .= ' GROUP BY a.student_id';
 2385: #    &Apache::lonnet::logthis('request = '.$/.$request);
 2386:     my $sth = $dbh->prepare($request);
 2387:     $sth->execute();
 2388:     $request = 
 2389:         'SELECT AVG(score),STD(score),MAX(score),MIN(score),COUNT(score) '.
 2390:         'FROM '.$stats_table;
 2391:     my ($ave,$std,$max,$min,$count) = &execute_SQL_request($dbh,$request);
 2392: #    &Apache::lonnet::logthis('request = '.$/.$request);
 2393:     
 2394:     $request = 'SELECT SUM(weight) FROM '.$weight_table.
 2395:         ' WHERE ('.$symb_restriction.')';
 2396:     my ($max_possible) = &execute_SQL_request($dbh,$request);
 2397:     # &Apache::lonnet::logthis('request = '.$/.$request);
 2398:     return($min,$max,$ave,$std,$count,$max_possible);
 2399: }
 2400: 
 2401: 
 2402: ########################################################
 2403: ########################################################
 2404: 
 2405: =pod
 2406: 
 2407: =item &count_stats
 2408: 
 2409: Inputs: $Sections, $enrollment, $symbs, $starttime,
 2410:         $endtime, $courseid
 2411: 
 2412: $Sections, $enrollment, $starttime, $endtime, and $courseid are the same as 
 2413: elsewhere in this module.  
 2414: $symbs is an array ref of symbs
 2415: 
 2416: Returns: minimum, maximum, mean, s.d., and number of students
 2417:   of the number of items correct on the given resources
 2418: 
 2419: =cut
 2420: 
 2421: ########################################################
 2422: ########################################################
 2423: sub count_stats {
 2424:     my ($Sections,$enrollment,$symbs,$starttime,$endtime,$courseid)=@_;
 2425:     if (! defined($courseid)) {
 2426:         $courseid = $ENV{'request.course.id'};
 2427:     }
 2428:     #
 2429:     &setup_table_names($courseid);
 2430:     my $dbh = &Apache::lonmysql::get_dbh();
 2431:     #
 2432:     my ($section_limits,$enrollment_limits)=
 2433:         &limit_by_section_and_status($Sections,$enrollment,'b');
 2434:     my $time_limits = &limit_by_start_end_time($starttime,$endtime,'a');
 2435:     my @Symbids = map { &get_symb_id($_); } @{$symbs};
 2436:     #
 2437:     my $stats_table = $courseid.'_problem_stats';
 2438:     my $symb_restriction = join(' OR ',map {'a.symb_id='.$_;} @Symbids);
 2439:     my $request = 'DROP TABLE '.$stats_table;
 2440:     $dbh->do($request);
 2441:     $request = 
 2442:         'CREATE TEMPORARY TABLE '.$stats_table.' '.
 2443:         'SELECT a.student_id,'.
 2444:         'COUNT(a.award) AS count FROM '.
 2445:         $performance_table.' AS a '.
 2446:         'LEFT JOIN '.$student_table.' AS b ON a.student_id=b.student_id '.
 2447:         'WHERE ('.$symb_restriction.')'.
 2448:         " AND a.award!='INCORRECT_ATTEMPTED'";
 2449:     if ($time_limits) {
 2450:         $request .= ' AND '.$time_limits;
 2451:     }
 2452:     if ($section_limits) {
 2453:         $request .= ' AND '.$section_limits;
 2454:     }
 2455:     if ($enrollment_limits) {
 2456:         $request .= ' AND '.$enrollment_limits;
 2457:     }
 2458:     $request .= ' GROUP BY a.student_id';
 2459: #    &Apache::lonnet::logthis('request = '.$/.$request);
 2460:     my $sth = $dbh->prepare($request);
 2461:     $sth->execute();
 2462:     $request = 
 2463:         'SELECT AVG(count),STD(count),MAX(count),MIN(count),COUNT(count) '.
 2464:         'FROM '.$stats_table;
 2465:     my ($ave,$std,$max,$min,$count) = &execute_SQL_request($dbh,$request);
 2466: #    &Apache::lonnet::logthis('request = '.$/.$request);
 2467:     return($min,$max,$ave,$std,$count);
 2468: }
 2469: 
 2470: ######################################################
 2471: ######################################################
 2472: 
 2473: =pod
 2474: 
 2475: =item get_student_data
 2476: 
 2477: =cut
 2478: 
 2479: ######################################################
 2480: ######################################################
 2481: sub get_student_data {
 2482:     my ($students,$courseid) = @_;
 2483:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
 2484:     &setup_table_names($courseid);
 2485:     my $dbh = &Apache::lonmysql::get_dbh();
 2486:     return undef if (! defined($dbh));
 2487:     my $request = 'SELECT '.
 2488:         'student_id, student '.
 2489:         'FROM '.$student_table;
 2490:     if (defined($students)) {
 2491:         $request .= ' WHERE ('.
 2492:             join(' OR ', map {'student_id='.
 2493:                                   &get_student_id($_->{'username'},
 2494:                                                   $_->{'domain'})
 2495:                               } @$students
 2496:                  ).')';
 2497:     }
 2498:     $request.= ' ORDER BY student_id';
 2499:     my $sth = $dbh->prepare($request);
 2500:     $sth->execute();
 2501:     if ($dbh->err) {
 2502:         &Apache::lonnet::logthis('error = '.$dbh->errstr());
 2503:         return undef;
 2504:     }
 2505:     my $dataset = $sth->fetchall_arrayref();
 2506:     if (ref($dataset) eq 'ARRAY' && scalar(@$dataset)>0) {
 2507:         return $dataset;
 2508:     }
 2509: }
 2510: 
 2511: sub RD_student_id    { return 0; }
 2512: sub RD_awarddetail   { return 1; }
 2513: sub RD_response_eval { return 2; }
 2514: sub RD_submission    { return 3; }
 2515: sub RD_timestamp     { return 4; }
 2516: sub RD_tries         { return 5; }
 2517: sub RD_sname         { return 6; }
 2518: 
 2519: sub get_response_data {
 2520:     my ($Sections,$enrollment,$symb,$response,$courseid) = @_;
 2521:     return undef if (! defined($symb) || 
 2522:                ! defined($response));
 2523:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
 2524:     #
 2525:     &setup_table_names($courseid);
 2526:     my $symb_id = &get_symb_id($symb);
 2527:     my $response_id = &get_part_id($response);
 2528:     #
 2529:     my $dbh = &Apache::lonmysql::get_dbh();
 2530:     return undef if (! defined($dbh));
 2531:     #
 2532:     my ($student_requirements,$enrollment_requirements) = 
 2533:         &limit_by_section_and_status($Sections,$enrollment,'d');
 2534:     my $request = 'SELECT '.
 2535:         'a.student_id, a.awarddetail, a.response_specific_value, '.
 2536:         'a.submission, b.timestamp, c.tries, d.student '.
 2537:         'FROM '.$fulldump_response_table.' AS a '.
 2538:         'LEFT JOIN '.$fulldump_timestamp_table.' AS b '.
 2539:         'ON a.symb_id=b.symb_id AND a.student_id=b.student_id AND '.
 2540:         'a.transaction = b.transaction '.
 2541:         'LEFT JOIN '.$fulldump_part_table.' AS c '.
 2542:         'ON a.symb_id=c.symb_id AND a.student_id=c.student_id AND '.        
 2543:         'a.part_id=c.part_id AND a.transaction = c.transaction '.
 2544:         'LEFT JOIN '.$student_table.' AS d '.
 2545:         'ON a.student_id=d.student_id '.
 2546:         'WHERE '.
 2547:         'a.symb_id='.$symb_id.' AND a.response_id='.$response_id;
 2548:     if (defined($student_requirements) || defined($enrollment_requirements)) {
 2549:         $request .= ' AND ';
 2550:         if (defined($student_requirements)) {
 2551:             $request .= $student_requirements.' AND ';
 2552:         }
 2553:         if (defined($enrollment_requirements)) {
 2554:             $request .= $enrollment_requirements.' AND ';
 2555:         }
 2556:         $request =~ s/( AND )$//;
 2557:     }
 2558:     $request .= ' ORDER BY b.timestamp';
 2559: #    &Apache::lonnet::logthis("request =\n".$request);
 2560:     my $sth = $dbh->prepare($request);
 2561:     $sth->execute();
 2562:     if ($dbh->err) {
 2563:         &Apache::lonnet::logthis('error = '.$dbh->errstr());
 2564:         return undef;
 2565:     }
 2566:     my $dataset = $sth->fetchall_arrayref();
 2567:     if (ref($dataset) eq 'ARRAY' && scalar(@$dataset)>0) {
 2568:         # Clear the \'s from around the submission
 2569:         for (my $i =0;$i<scalar(@$dataset);$i++) {
 2570:             $dataset->[$i]->[3] =~ s/(\'$|^\')//g;
 2571:         }
 2572:         return $dataset;
 2573:     }
 2574: }
 2575: 
 2576: 
 2577: sub RDs_awarddetail   { return 3; }
 2578: sub RDs_submission    { return 2; }
 2579: sub RDs_timestamp     { return 1; }
 2580: sub RDs_tries         { return 0; }
 2581: sub RDs_awarded       { return 4; }
 2582: 
 2583: sub get_response_data_by_student {
 2584:     my ($student,$symb,$response,$courseid) = @_;
 2585:     return undef if (! defined($symb) || 
 2586:                      ! defined($response));
 2587:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
 2588:     #
 2589:     &setup_table_names($courseid);
 2590:     my $symb_id = &get_symb_id($symb);
 2591:     my $response_id = &get_part_id($response);
 2592:     #
 2593:     my $student_id = &get_student_id($student->{'username'},
 2594:                                      $student->{'domain'});
 2595:     #
 2596:     my $dbh = &Apache::lonmysql::get_dbh();
 2597:     return undef if (! defined($dbh));
 2598:     my $request = 'SELECT '.
 2599:         'c.tries, b.timestamp, a.submission, a.awarddetail, e.awarded '.
 2600:         'FROM '.$fulldump_response_table.' AS a '.
 2601:         'LEFT JOIN '.$fulldump_timestamp_table.' AS b '.
 2602:         'ON a.symb_id=b.symb_id AND a.student_id=b.student_id AND '.
 2603:         'a.transaction = b.transaction '.
 2604:         'LEFT JOIN '.$fulldump_part_table.' AS c '.
 2605:         'ON a.symb_id=c.symb_id AND a.student_id=c.student_id AND '.        
 2606:         'a.part_id=c.part_id AND a.transaction = c.transaction '.
 2607:         'LEFT JOIN '.$student_table.' AS d '.
 2608:         'ON a.student_id=d.student_id '.
 2609:         'LEFT JOIN '.$performance_table.' AS e '.
 2610:         'ON a.symb_id=e.symb_id AND a.part_id=e.part_id AND '.
 2611:         'a.student_id=e.student_id AND c.tries=e.tries '.
 2612:         'WHERE '.
 2613:         'a.symb_id='.$symb_id.' AND a.response_id='.$response_id.
 2614:         ' AND a.student_id='.$student_id.' ORDER BY b.timestamp';
 2615: #    &Apache::lonnet::logthis("request =\n".$request);
 2616:     my $sth = $dbh->prepare($request);
 2617:     $sth->execute();
 2618:     if ($dbh->err) {
 2619:         &Apache::lonnet::logthis('error = '.$dbh->errstr());
 2620:         return undef;
 2621:     }
 2622:     my $dataset = $sth->fetchall_arrayref();
 2623:     if (ref($dataset) eq 'ARRAY' && scalar(@$dataset)>0) {
 2624:         # Clear the \'s from around the submission
 2625:         for (my $i =0;$i<scalar(@$dataset);$i++) {
 2626:             $dataset->[$i]->[2] =~ s/(\'$|^\')//g;
 2627:         }
 2628:         return $dataset;
 2629:     }
 2630:     return undef; # error occurred
 2631: }
 2632: 
 2633: sub RT_student_id { return 0; }
 2634: sub RT_awarded    { return 1; }
 2635: sub RT_tries      { return 2; }
 2636: sub RT_timestamp  { return 3; }
 2637: 
 2638: sub get_response_time_data {
 2639:     my ($students,$symb,$part,$courseid) = @_;
 2640:     return undef if (! defined($symb) || 
 2641:                      ! defined($part));
 2642:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
 2643:     #
 2644:     &setup_table_names($courseid);
 2645:     my $symb_id = &get_symb_id($symb);
 2646:     my $part_id = &get_part_id($part);
 2647:     #
 2648:     my $dbh = &Apache::lonmysql::get_dbh();
 2649:     return undef if (! defined($dbh));
 2650:     my $request = 'SELECT '.
 2651:         'a.student_id, a.awarded, a.tries, b.timestamp '.
 2652:         'FROM '.$fulldump_part_table.' AS a '.
 2653:         'NATURAL LEFT JOIN '.$fulldump_timestamp_table.' AS b '.
 2654: #        'ON a.symb_id=b.symb_id AND a.student_id=b.student_id AND '.
 2655: #        'a.transaction = b.transaction '.
 2656:         'WHERE '.
 2657:         'a.symb_id='.$symb_id.' AND a.part_id='.$part_id;
 2658:     if (defined($students)) {
 2659:         $request .= ' AND ('.
 2660:             join(' OR ', map {'a.student_id='.
 2661:                                   &get_student_id($_->{'username'},
 2662:                                                   $_->{'domain'})
 2663:                               } @$students
 2664:                  ).')';
 2665:     }
 2666:     $request .= ' ORDER BY b.timestamp';
 2667: #    &Apache::lonnet::logthis("request =\n".$request);
 2668:     my $sth = $dbh->prepare($request);
 2669:     $sth->execute();
 2670:     if ($dbh->err) {
 2671:         &Apache::lonnet::logthis('error = '.$dbh->errstr());
 2672:         return undef;
 2673:     }
 2674:     my $dataset = $sth->fetchall_arrayref();
 2675:     if (ref($dataset) eq 'ARRAY' && scalar(@$dataset)>0) {
 2676:         return $dataset;
 2677:     }
 2678: 
 2679: }
 2680: 
 2681: ################################################
 2682: ################################################
 2683: 
 2684: =pod
 2685: 
 2686: =item &get_student_scores($Sections,$Symbs,$enrollment,$courseid)
 2687: 
 2688: =cut
 2689: 
 2690: ################################################
 2691: ################################################
 2692: sub get_student_scores {
 2693:     my ($Sections,$Symbs,$enrollment,$courseid,$starttime,$endtime) = @_;
 2694:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
 2695:     &setup_table_names($courseid);
 2696:     my $dbh = &Apache::lonmysql::get_dbh();
 2697:     return (undef) if (! defined($dbh));
 2698:     my $tmptable = $courseid.'_temp_'.time;
 2699:     #
 2700:     my $symb_requirements;
 2701:     if (defined($Symbs)  && @$Symbs) {
 2702:         $symb_requirements = '('.
 2703:             join(' OR ', map{ "(a.symb_id='".&get_symb_id($_->{'symb'}).
 2704:                               "' AND a.part_id='".&get_part_id($_->{'part'}).
 2705:                               "')"
 2706:                               } @$Symbs).')';
 2707:     }
 2708:     #
 2709:     my $student_requirements;
 2710:     if ( (defined($Sections) && $Sections->[0] ne 'all')) {
 2711:         $student_requirements = '('.
 2712:             join(' OR ', map { "b.section='".$_."'" } @$Sections
 2713:                  ).')';
 2714:     }
 2715:     #
 2716:     my $enrollment_requirements=undef;
 2717:     if (defined($enrollment) && $enrollment ne 'Any') {
 2718:         $enrollment_requirements = "b.status='".$enrollment."'";
 2719:     }
 2720:     #
 2721:     my $time_requirements = undef;
 2722:     if (defined($starttime)) {
 2723:         $time_requirements .= "a.timestamp>='".$starttime."'";
 2724:         if (defined($endtime)) {
 2725:             $time_requirements .= " AND a.timestamp<='".$endtime."'";
 2726:         }
 2727:     } elsif (defined($endtime)) {
 2728:         $time_requirements .= "a.timestamp<='".$endtime."'";
 2729:     }
 2730:     ##
 2731:     ##
 2732:     my $request = 'CREATE TEMPORARY TABLE IF NOT EXISTS '.$tmptable.
 2733:         ' SELECT a.student_id,SUM(a.awarded) AS score FROM '.
 2734:         $performance_table.' AS a ';
 2735:     if (defined($student_requirements) || defined($enrollment_requirements)) {
 2736:         $request .= ' NATURAL LEFT JOIN '.$student_table.' AS b ';
 2737:     }
 2738:     if (defined($symb_requirements)      || 
 2739:         defined($student_requirements)   ||
 2740:         defined($enrollment_requirements) ) {
 2741:         $request .= ' WHERE ';
 2742:     }
 2743:     if (defined($symb_requirements)) {
 2744:         $request .= $symb_requirements.' AND ';
 2745:     }
 2746:     if (defined($student_requirements)) {
 2747:         $request .= $student_requirements.' AND ';
 2748:     }
 2749:     if (defined($enrollment_requirements)) {
 2750:         $request .= $enrollment_requirements.' AND ';
 2751:     }
 2752:     if (defined($time_requirements)) {
 2753:         $request .= $time_requirements.' AND ';
 2754:     }
 2755:     $request =~ s/ AND $//; # Strip of the trailing ' AND '.
 2756:     $request .= ' GROUP BY a.student_id';
 2757: #    &Apache::lonnet::logthis("request = \n".$request);
 2758:     my $sth = $dbh->prepare($request);
 2759:     $sth->execute();
 2760:     if ($dbh->err) {
 2761:         &Apache::lonnet::logthis('error = '.$dbh->errstr());
 2762:         return undef;
 2763:     }
 2764:     $request = 'SELECT score,COUNT(*) FROM '.$tmptable.' GROUP BY score';
 2765: #    &Apache::lonnet::logthis("request = \n".$request);
 2766:     $sth = $dbh->prepare($request);
 2767:     $sth->execute();
 2768:     if ($dbh->err) {
 2769:         &Apache::lonnet::logthis('error = '.$dbh->errstr());
 2770:         return undef;
 2771:     }
 2772:     my $dataset = $sth->fetchall_arrayref();
 2773:     return $dataset;
 2774: }
 2775: 
 2776: ################################################
 2777: ################################################
 2778: 
 2779: =pod
 2780: 
 2781: =item &setup_table_names()
 2782: 
 2783: input: course id
 2784: 
 2785: output: none
 2786: 
 2787: Cleans up the package variables for local caching.
 2788: 
 2789: =cut
 2790: 
 2791: ################################################
 2792: ################################################
 2793: sub setup_table_names {
 2794:     my ($courseid) = @_;
 2795:     if (! defined($courseid)) {
 2796:         $courseid = $ENV{'request.course.id'};
 2797:     }
 2798:     #
 2799:     if (! defined($current_course) || $current_course ne $courseid) {
 2800:         # Clear out variables
 2801:         $have_read_part_table = 0;
 2802:         undef(%ids_by_part);
 2803:         undef(%parts_by_id);
 2804:         $have_read_symb_table = 0;
 2805:         undef(%ids_by_symb);
 2806:         undef(%symbs_by_id);
 2807:         $have_read_student_table = 0;
 2808:         undef(%ids_by_student);
 2809:         undef(%students_by_id);
 2810:         #
 2811:         $current_course = $courseid;
 2812:     }
 2813:     #
 2814:     # Set up database names
 2815:     my $base_id = $courseid;
 2816:     $symb_table        = $base_id.'_'.'symb';
 2817:     $part_table        = $base_id.'_'.'part';
 2818:     $student_table     = $base_id.'_'.'student';
 2819:     $performance_table = $base_id.'_'.'performance';
 2820:     $parameters_table  = $base_id.'_'.'parameters';
 2821:     $fulldump_part_table      = $base_id.'_'.'partdata';
 2822:     $fulldump_response_table  = $base_id.'_'.'responsedata';
 2823:     $fulldump_timestamp_table = $base_id.'_'.'timestampdata';
 2824:     $weight_table             = $base_id.'_'.'weight';
 2825:     #
 2826:     @Tables = (
 2827:                $symb_table,
 2828:                $part_table,
 2829:                $student_table,
 2830:                $performance_table,
 2831:                $parameters_table,
 2832:                $fulldump_part_table,
 2833:                $fulldump_response_table,
 2834:                $fulldump_timestamp_table,
 2835:                $weight_table,
 2836:                );
 2837:     return;
 2838: }
 2839: 
 2840: ################################################
 2841: ################################################
 2842: 
 2843: =pod
 2844: 
 2845: =back
 2846: 
 2847: =item End of Local Data Caching Subroutines
 2848: 
 2849: =cut
 2850: 
 2851: ################################################
 2852: ################################################
 2853: 
 2854: } # End scope of table identifiers
 2855: 
 2856: ################################################
 2857: ################################################
 2858: 
 2859: =pod
 2860: 
 2861: =head3 Classlist Subroutines
 2862: 
 2863: =item &get_classlist();
 2864: 
 2865: Retrieve the classist of a given class or of the current class.  Student
 2866: information is returned from the classlist.db file and, if needed,
 2867: from the students environment.
 2868: 
 2869: Optional arguments are $cid, $cdom, and $cnum (course id, course domain,
 2870: and course number, respectively).  Any omitted arguments will be taken 
 2871: from the current environment ($ENV{'request.course.id'},
 2872: $ENV{'course.'.$cid.'.domain'}, and $ENV{'course.'.$cid.'.num'}).
 2873: 
 2874: Returns a reference to a hash which contains:
 2875:  keys    '$sname:$sdom'
 2876:  values  [$sdom,$sname,$end,$start,$id,$section,$fullname,$status,$type]
 2877: 
 2878: The constant values CL_SDOM, CL_SNAME, CL_END, etc. can be used
 2879: as indices into the returned list to future-proof clients against
 2880: changes in the list order.
 2881: 
 2882: =cut
 2883: 
 2884: ################################################
 2885: ################################################
 2886: 
 2887: sub CL_SDOM     { return 0; }
 2888: sub CL_SNAME    { return 1; }
 2889: sub CL_END      { return 2; }
 2890: sub CL_START    { return 3; }
 2891: sub CL_ID       { return 4; }
 2892: sub CL_SECTION  { return 5; }
 2893: sub CL_FULLNAME { return 6; }
 2894: sub CL_STATUS   { return 7; }
 2895: sub CL_TYPE     { return 8; }
 2896: 
 2897: sub get_classlist {
 2898:     my ($cid,$cdom,$cnum) = @_;
 2899:     $cid = $cid || $ENV{'request.course.id'};
 2900:     $cdom = $cdom || $ENV{'course.'.$cid.'.domain'};
 2901:     $cnum = $cnum || $ENV{'course.'.$cid.'.num'};
 2902:     my $now = time;
 2903:     #
 2904:     my %classlist=&Apache::lonnet::dump('classlist',$cdom,$cnum);
 2905:     while (my ($student,$info) = each(%classlist)) {
 2906:         if ($student =~ /^(con_lost|error|no_such_host)/i) {
 2907:             &Apache::lonnet::logthis('get_classlist error for '.$cid.':'.$student);
 2908:             return undef;
 2909:         }
 2910:         my ($sname,$sdom) = split(/:/,$student);
 2911:         my @Values = split(/:/,$info);
 2912:         my ($end,$start,$id,$section,$fullname,$type);
 2913:         if (@Values > 2) {
 2914:             ($end,$start,$id,$section,$fullname,$type) = @Values;
 2915:         } else { # We have to get the data ourselves
 2916:             ($end,$start) = @Values;
 2917:             $section = &Apache::lonnet::getsection($sdom,$sname,$cid);
 2918:             my %info=&Apache::lonnet::get('environment',
 2919:                                           ['firstname','middlename',
 2920:                                            'lastname','generation','id'],
 2921:                                           $sdom, $sname);
 2922:             my ($tmp) = keys(%info);
 2923:             if ($tmp =~/^(con_lost|error|no_such_host)/i) {
 2924:                 $fullname = 'not available';
 2925:                 $id = 'not available';
 2926:                 &Apache::lonnet::logthis('unable to retrieve environment '.
 2927:                                          'for '.$sname.':'.$sdom);
 2928:             } else {
 2929:                 $fullname = &ProcessFullName(@info{qw/lastname generation 
 2930:                                                        firstname middlename/});
 2931:                 $id = $info{'id'};
 2932:             }
 2933:             # Update the classlist with this students information
 2934:             if ($fullname ne 'not available') {
 2935:                 my $enrolldata = join(':',$end,$start,$id,$section,$fullname);
 2936:                 my $reply=&Apache::lonnet::cput('classlist',
 2937:                                                 {$student => $enrolldata},
 2938:                                                 $cdom,$cnum);
 2939:                 if ($reply !~ /^(ok|delayed)/) {
 2940:                     &Apache::lonnet::logthis('Unable to update classlist for '.
 2941:                                              'student '.$sname.':'.$sdom.
 2942:                                              ' error:'.$reply);
 2943:                 }
 2944:             }
 2945:         }
 2946:         my $status='Expired';
 2947:         if(((!$end) || $now < $end) && ((!$start) || ($now > $start))) {
 2948:             $status='Active';
 2949:         }
 2950:         $classlist{$student} = 
 2951:             [$sdom,$sname,$end,$start,$id,$section,$fullname,$status,$type];
 2952:     }
 2953:     if (wantarray()) {
 2954:         return (\%classlist,['domain','username','end','start','id',
 2955:                              'section','fullname','status','type']);
 2956:     } else {
 2957:         return \%classlist;
 2958:     }
 2959: }
 2960: 
 2961: # ----- END HELPER FUNCTIONS --------------------------------------------
 2962: 
 2963: 1;
 2964: __END__
 2965: 
 2966: 

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