Annotation of loncom/interface/loncoursedata.pm, revision 1.106

1.1       stredwic    1: # The LearningOnline Network with CAPA
                      2: #
1.106   ! matthew     3: # $Id: loncoursedata.pm,v 1.105 2003/10/20 20:42:39 matthew Exp $
1.1       stredwic    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: 
1.22      stredwic   37: Set of functions that download and process student and course information.
1.1       stredwic   38: 
                     39: =head1 PACKAGES USED
                     40: 
                     41:  Apache::Constants qw(:common :http)
                     42:  Apache::lonnet()
1.22      stredwic   43:  Apache::lonhtmlcommon
1.1       stredwic   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();
1.13      stredwic   54: use Apache::lonhtmlcommon;
1.57      matthew    55: use Time::HiRes;
                     56: use Apache::lonmysql;
1.1       stredwic   57: use HTML::TokeParser;
                     58: use GDBM_File;
                     59: 
                     60: =pod
                     61: 
                     62: =head1 DOWNLOAD INFORMATION
                     63: 
1.22      stredwic   64: This section contains all the functions that get data from other servers 
                     65: and/or itself.
1.1       stredwic   66: 
                     67: =cut
                     68: 
1.50      matthew    69: ####################################################
                     70: ####################################################
1.45      matthew    71: 
                     72: =pod
                     73: 
                     74: =item &get_sequence_assessment_data()
                     75: 
                     76: AT THIS TIME THE USE OF THIS FUNCTION IS *NOT* RECOMMENDED
                     77: 
                     78: Use lonnavmaps to build a data structure describing the order and 
                     79: assessment contents of each sequence in the current course.
                     80: 
                     81: The returned structure is a hash reference. 
                     82: 
1.61      matthew    83: { title => 'title',
                     84:   symb  => 'symb',
                     85:   src   => '/s/o/u/r/c/e',
1.45      matthew    86:   type  => (container|assessment),
1.50      matthew    87:   num_assess   => 2,               # only for container
1.45      matthew    88:   parts        => [11,13,15],      # only for assessment
1.50      matthew    89:   response_ids => [12,14,16],      # only for assessment
                     90:   contents     => [........]       # only for container
1.45      matthew    91: }
                     92: 
1.50      matthew    93: $hash->{'contents'} is a reference to an array of hashes of the same structure.
                     94: 
                     95: Also returned are array references to the sequences and assessments contained
                     96: in the course.
1.49      matthew    97: 
1.45      matthew    98: 
                     99: =cut
                    100: 
1.50      matthew   101: ####################################################
                    102: ####################################################
1.45      matthew   103: sub get_sequence_assessment_data {
                    104:     my $fn=$ENV{'request.course.fn'};
                    105:     ##
                    106:     ## use navmaps
1.83      bowersj2  107:     my $navmap = Apache::lonnavmaps::navmap->new();
1.45      matthew   108:     if (!defined($navmap)) {
                    109:         return 'Can not open Coursemap';
                    110:     }
1.75      matthew   111:     # We explicity grab the top level map because I am not sure we
                    112:     # are pulling it from the iterator.
                    113:     my $top_level_map = $navmap->getById('0.0');
                    114:     #
1.45      matthew   115:     my $iterator = $navmap->getIterator(undef, undef, undef, 1);
1.61      matthew   116:     my $curRes = $iterator->next(); # Top level sequence
1.45      matthew   117:     ##
                    118:     ## Prime the pump 
                    119:     ## 
                    120:     ## We are going to loop until we run out of sequences/pages to explore for
                    121:     ## resources.  This means we have to start out with something to look
                    122:     ## at.
1.76      matthew   123:     my $title = $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
1.75      matthew   124:     my $symb  = $top_level_map->symb();
                    125:     my $src   = $top_level_map->src();
                    126:     my $randompick = $top_level_map->randompick();
1.45      matthew   127:     #
1.49      matthew   128:     my @Sequences; 
                    129:     my @Assessments;
1.45      matthew   130:     my @Nested_Sequences = ();   # Stack of sequences, keeps track of depth
                    131:     my $top = { title    => $title,
1.52      matthew   132:                 src      => $src,
1.45      matthew   133:                 symb     => $symb,
                    134:                 type     => 'container',
                    135:                 num_assess => 0,
1.53      matthew   136:                 num_assess_parts => 0,
1.75      matthew   137:                 contents   => [], 
                    138:                 randompick => $randompick,
                    139:             };
1.49      matthew   140:     push (@Sequences,$top);
1.45      matthew   141:     push (@Nested_Sequences, $top);
                    142:     #
                    143:     # We need to keep track of which sequences contain homework problems
                    144:     # 
1.78      matthew   145:     my $previous_too;
1.52      matthew   146:     my $previous;
1.45      matthew   147:     while (scalar(@Nested_Sequences)) {
1.78      matthew   148:         $previous_too = $previous;
1.50      matthew   149:         $previous = $curRes;
1.45      matthew   150:         $curRes = $iterator->next();
                    151:         my $currentmap = $Nested_Sequences[-1]; # Last one on the stack
                    152:         if ($curRes == $iterator->BEGIN_MAP()) {
1.78      matthew   153:             if (! ref($previous)) {
                    154:                 $previous = $previous_too;
                    155:             }
                    156:             if (! ref($previous)) {
                    157:                 next;
                    158:             }
1.45      matthew   159:             # get the map itself, instead of BEGIN_MAP
1.51      matthew   160:             $title = $previous->title();
1.84      matthew   161:             $title =~ s/\:/\&\#058;/g;
1.51      matthew   162:             $symb  = $previous->symb();
                    163:             $src   = $previous->src();
1.81      matthew   164:             # pick up the filename if there is no title available
                    165:             if (! defined($title) || $title eq '') {
                    166:                 ($title) = ($src=~/\/([^\/]*)$/);
                    167:             }
1.75      matthew   168:             $randompick = $previous->randompick();
1.45      matthew   169:             my $newmap = { title    => $title,
                    170:                            src      => $src,
                    171:                            symb     => $symb,
                    172:                            type     => 'container',
                    173:                            num_assess => 0,
1.75      matthew   174:                            randompick => $randompick,
1.45      matthew   175:                            contents   => [],
                    176:                        };
                    177:             push (@{$currentmap->{'contents'}},$newmap); # this is permanent
1.49      matthew   178:             push (@Sequences,$newmap);
1.45      matthew   179:             push (@Nested_Sequences, $newmap); # this is a stack
                    180:             next;
                    181:         }
                    182:         if ($curRes == $iterator->END_MAP()) {
                    183:             pop(@Nested_Sequences);
                    184:             next;
                    185:         }
                    186:         next if (! ref($curRes));
1.50      matthew   187:         next if (! $curRes->is_problem());# && !$curRes->randomout);
1.45      matthew   188:         # Okay, from here on out we only deal with assessments
                    189:         $title = $curRes->title();
1.84      matthew   190:         $title =~ s/\:/\&\#058;/g;
1.45      matthew   191:         $symb  = $curRes->symb();
                    192:         $src   = $curRes->src();
                    193:         my $parts = $curRes->parts();
1.87      matthew   194:         my %partdata;
                    195:         foreach my $part (@$parts) {
1.88      matthew   196:             my @Responses = $curRes->responseType($part);
                    197:             my @Ids       = $curRes->responseIds($part);
                    198:             $partdata{$part}->{'ResponseTypes'}= \@Responses;
                    199:             $partdata{$part}->{'ResponseIds'}  = \@Ids;
1.91      matthew   200:             # Count how many responses of each type there are in this part
                    201:             foreach (@Responses) {
                    202:                 $partdata{$part}->{$_}++;
                    203:             }
1.87      matthew   204:         }
1.45      matthew   205:         my $assessment = { title => $title,
                    206:                            src   => $src,
                    207:                            symb  => $symb,
                    208:                            type  => 'assessment',
1.53      matthew   209:                            parts => $parts,
                    210:                            num_parts => scalar(@$parts),
1.87      matthew   211:                            partdata => \%partdata,
1.45      matthew   212:                        };
1.49      matthew   213:         push(@Assessments,$assessment);
1.45      matthew   214:         push(@{$currentmap->{'contents'}},$assessment);
                    215:         $currentmap->{'num_assess'}++;
1.53      matthew   216:         $currentmap->{'num_assess_parts'}+= scalar(@$parts);
1.45      matthew   217:     }
1.58      matthew   218:     $navmap->untieHashes();
1.49      matthew   219:     return ($top,\@Sequences,\@Assessments);
1.45      matthew   220: }
1.50      matthew   221: 
1.4       stredwic  222: sub LoadDiscussion {
1.13      stredwic  223:     my ($courseID)=@_;
1.5       minaeibi  224:     my %Discuss=();
                    225:     my %contrib=&Apache::lonnet::dump(
                    226:                 $courseID,
                    227:                 $ENV{'course.'.$courseID.'.domain'},
                    228:                 $ENV{'course.'.$courseID.'.num'});
                    229: 				 
                    230:     #my %contrib=&DownloadCourseInformation($name, $courseID, 0);
                    231: 
1.4       stredwic  232:     foreach my $temp(keys %contrib) {
                    233: 	if ($temp=~/^version/) {
                    234: 	    my $ver=$contrib{$temp};
                    235: 	    my ($dummy,$prb)=split(':',$temp);
                    236: 	    for (my $idx=1; $idx<=$ver; $idx++ ) {
                    237: 		my $name=$contrib{"$idx:$prb:sendername"};
1.5       minaeibi  238: 		$Discuss{"$name:$prb"}=$idx;	
1.4       stredwic  239: 	    }
                    240: 	}
                    241:     }       
1.5       minaeibi  242: 
                    243:     return \%Discuss;
1.1       stredwic  244: }
                    245: 
1.71      matthew   246: ################################################
                    247: ################################################
                    248: 
                    249: =pod
                    250: 
                    251: =item &GetUserName(username,userdomain)
                    252: 
                    253: Returns a hash with the following entries:
                    254:    'firstname', 'middlename', 'lastname', 'generation', and 'fullname'
                    255: 
                    256:    'fullname' is the result of &Apache::loncoursedata::ProcessFullName.
                    257: 
                    258: =cut
                    259: 
                    260: ################################################
                    261: ################################################
                    262: sub GetUserName {
                    263:     my ($username,$userdomain) = @_;
                    264:     $username = $ENV{'user.name'} if (! defined($username));
                    265:     $userdomain = $ENV{'user.domain'} if (! defined($username));
                    266:     my %userenv = &Apache::lonnet::get('environment',
                    267:                            ['firstname','middlename','lastname','generation'],
                    268:                                        $userdomain,$username);
                    269:     $userenv{'fullname'} = &ProcessFullName($userenv{'lastname'},
                    270:                                             $userenv{'generation'},
                    271:                                             $userenv{'firstname'},
                    272:                                             $userenv{'middlename'});
                    273:     return %userenv;
                    274: }
                    275: 
                    276: ################################################
                    277: ################################################
                    278: 
1.1       stredwic  279: =pod
                    280: 
                    281: =item &ProcessFullName()
                    282: 
                    283: Takes lastname, generation, firstname, and middlename (or some partial
                    284: set of this data) and returns the full name version as a string.  Format
                    285: is Lastname generation, firstname middlename or a subset of this.
                    286: 
                    287: =cut
                    288: 
1.71      matthew   289: ################################################
                    290: ################################################
1.1       stredwic  291: sub ProcessFullName {
                    292:     my ($lastname, $generation, $firstname, $middlename)=@_;
                    293:     my $Str = '';
                    294: 
1.34      matthew   295:     # Strip whitespace preceeding & following name components.
                    296:     $lastname   =~ s/(\s+$|^\s+)//g;
                    297:     $generation =~ s/(\s+$|^\s+)//g;
                    298:     $firstname  =~ s/(\s+$|^\s+)//g;
                    299:     $middlename =~ s/(\s+$|^\s+)//g;
                    300: 
1.1       stredwic  301:     if($lastname ne '') {
1.34      matthew   302: 	$Str .= $lastname;
                    303: 	$Str .= ' '.$generation if ($generation ne '');
                    304: 	$Str .= ',';
                    305:         $Str .= ' '.$firstname  if ($firstname ne '');
                    306:         $Str .= ' '.$middlename if ($middlename ne '');
1.1       stredwic  307:     } else {
1.34      matthew   308:         $Str .= $firstname      if ($firstname ne '');
                    309:         $Str .= ' '.$middlename if ($middlename ne '');
                    310:         $Str .= ' '.$generation if ($generation ne '');
1.1       stredwic  311:     }
                    312: 
                    313:     return $Str;
                    314: }
                    315: 
1.46      matthew   316: ################################################
                    317: ################################################
                    318: 
                    319: =pod
                    320: 
1.47      matthew   321: =item &make_into_hash($values);
                    322: 
                    323: Returns a reference to a hash as described by $values.  $values is
                    324: assumed to be the result of 
1.57      matthew   325:     join(':',map {&Apache::lonnet::escape($_)} %orighash);
1.47      matthew   326: 
                    327: This is a helper function for get_current_state.
                    328: 
                    329: =cut
                    330: 
                    331: ################################################
                    332: ################################################
                    333: sub make_into_hash {
                    334:     my $values = shift;
                    335:     my %tmp = map { &Apache::lonnet::unescape($_); }
                    336:                                            split(':',$values);
                    337:     return \%tmp;
                    338: }
                    339: 
                    340: 
                    341: ################################################
                    342: ################################################
                    343: 
                    344: =pod
                    345: 
1.57      matthew   346: =head1 LOCAL DATA CACHING SUBROUTINES
                    347: 
                    348: The local caching is done using MySQL.  There is no fall-back implementation
                    349: if MySQL is not running.
                    350: 
                    351: The programmers interface is to call &get_current_state() or some other
                    352: primary interface subroutine (described below).  The internals of this 
                    353: storage system are documented here.
                    354: 
                    355: There are six tables used to store student performance data (the results of
                    356: a dumpcurrent).  Each of these tables is created in MySQL with a name of
                    357: $courseid_*****, where ***** is 'symb', 'part', or whatever is appropriate 
                    358: for the table.  The tables and their purposes are described below.
                    359: 
                    360: Some notes before we get started.
                    361: 
                    362: Each table must have a PRIMARY KEY, which is a column or set of columns which
                    363: will serve to uniquely identify a row of data.  NULL is not allowed!
                    364: 
                    365: INDEXes work best on integer data.
                    366: 
                    367: JOIN is used to combine data from many tables into one output.
                    368: 
                    369: lonmysql.pm is used for some of the interface, specifically the table creation
                    370: calls.  The inserts are done in bulk by directly calling the database handler.
                    371: The SELECT ... JOIN statement used to retrieve the data does not have an
                    372: interface in lonmysql.pm and I shudder at the thought of writing one.
                    373: 
                    374: =head3 Table Descriptions
                    375: 
                    376: =over 4
                    377: 
1.89      matthew   378: =item Tables used to store meta information
                    379: 
                    380: The following tables hold data required to keep track of the current status
                    381: of a students data in the tables or to look up the students data in the tables.
                    382: 
                    383: =over 4
                    384: 
1.57      matthew   385: =item $symb_table
                    386: 
                    387: The symb_table has two columns.  The first is a 'symb_id' and the second
                    388: is the text name for the 'symb' (limited to 64k).  The 'symb_id' is generated
                    389: automatically by MySQL so inserts should be done on this table with an
                    390: empty first element.  This table has its PRIMARY KEY on the 'symb_id'.
                    391: 
                    392: =item $part_table
                    393: 
                    394: The part_table has two columns.  The first is a 'part_id' and the second
                    395: is the text name for the 'part' (limited to 100 characters).  The 'part_id' is
                    396: generated automatically by MySQL so inserts should be done on this table with
                    397: an empty first element.  This table has its PRIMARY KEY on the 'part' (100
                    398: characters) and a KEY on 'part_id'.
                    399: 
                    400: =item $student_table
                    401: 
                    402: The student_table has two columns.  The first is a 'student_id' and the second
                    403: is the text description of the 'student' (typically username:domain) (less
                    404: than 100 characters).  The 'student_id' is automatically generated by MySQL.
                    405: The use of the name 'student_id' is loaded, I know, but this ID is used ONLY 
                    406: internally to the MySQL database and is not the same as the students ID 
                    407: (stored in the students environment).  This table has its PRIMARY KEY on the
                    408: 'student' (100 characters).
                    409: 
1.87      matthew   410: =item $studentdata_table
1.57      matthew   411: 
1.89      matthew   412: The studentdata_table has four columns:  'student_id' (the unique id of 
                    413: the student), 'updatetime' (the time the students data was last updated),
                    414: 'fullupdatetime' (the time the students full data was last updated),
                    415: 'section', and 'classification'( the students current classification).
                    416: This table has its PRIMARY KEY on 'student_id'.
                    417: 
                    418: =back 
                    419: 
                    420: =item Tables used to store current status data
                    421: 
                    422: The following tables store data only about the students current status on 
                    423: a problem, meaning only the data related to the last attempt on a problem.
                    424: 
                    425: =over 4
1.57      matthew   426: 
                    427: =item $performance_table
                    428: 
                    429: The performance_table has 9 columns.  The first three are 'symb_id', 
                    430: 'student_id', and 'part_id'.  These comprise the PRIMARY KEY for this table
                    431: and are directly related to the $symb_table, $student_table, and $part_table
                    432: described above.  MySQL does better indexing on numeric items than text,
                    433: so we use these three "index tables".  The remaining columns are
                    434: 'solved', 'tries', 'awarded', 'award', 'awarddetail', and 'timestamp'.
                    435: These are either the MySQL type TINYTEXT or various integers ('tries' and 
                    436: 'timestamp').  This table has KEYs of 'student_id' and 'symb_id'.
                    437: For use of this table, see the functions described below.
                    438: 
                    439: =item $parameters_table
                    440: 
                    441: The parameters_table holds the data that does not fit neatly into the
                    442: performance_table.  The parameters table has four columns: 'symb_id',
                    443: 'student_id', 'parameter', and 'value'.  'symb_id', 'student_id', and
                    444: 'parameter' comprise the PRIMARY KEY for this table.  'parameter' is 
                    445: limited to 255 characters.  'value' is limited to 64k characters.
                    446: 
                    447: =back
                    448: 
1.89      matthew   449: =item Tables used for storing historic data
                    450: 
                    451: The following tables are used to store almost all of the transactions a student
                    452: has made on a homework problem.  See loncapa/docs/homework/datastorage for 
                    453: specific information about each of the parameters stored.  
                    454: 
                    455: =over 4
                    456: 
                    457: =item $fulldump_response_table
                    458: 
                    459: The response table holds data (documented in loncapa/docs/homework/datastorage)
                    460: associated with a particular response id which is stored when a student 
                    461: attempts a problem.  The following are the columns of the table, in order:
                    462: 'symb_id','part_id','response_id','student_id','transaction','tries',
1.93      matthew   463: 'awarddetail', 'response_specific' (data particular to the response
1.89      matthew   464: type), 'response_specific_value', and 'submission (the text of the students
                    465: submission).  The primary key is based on the first five columns listed above.
                    466: 
                    467: =item $fulldump_part_table
                    468: 
                    469: The part table holds data (documented in loncapa/docs/homework/datastorage)
                    470: associated with a particular part id which is stored when a student attempts
                    471: a problem.  The following are the columns of the table, in order:
                    472: 'symb_id','part_id','student_id','transaction','tries','award','awarded',
                    473: and 'previous'.  The primary key is based on the first five columns listed 
                    474: above.
                    475: 
                    476: =item $fulldump_timestamp_table
                    477: 
                    478: The timestamp table holds the timestamps of the transactions which are
                    479: stored in $fulldump_response_table and $fulldump_part_table.  This data is
                    480: about both the response and part data.  Columns: 'symb_id','student_id',
                    481: 'transaction', and 'timestamp'.  
                    482: The primary key is based on the first 3 columns.
                    483: 
                    484: =back
                    485: 
                    486: =back
                    487: 
1.57      matthew   488: =head3 Important Subroutines
                    489: 
                    490: Here is a brief overview of the subroutines which are likely to be of 
                    491: interest:
                    492: 
                    493: =over 4
                    494: 
                    495: =item &get_current_state(): programmers interface.
                    496: 
                    497: =item &init_dbs(): table creation
                    498: 
                    499: =item &update_student_data(): data storage calls
                    500: 
                    501: =item &get_student_data_from_performance_cache(): data retrieval
                    502: 
                    503: =back
                    504: 
                    505: =head3 Main Documentation
                    506: 
                    507: =over 4
                    508: 
                    509: =cut
                    510: 
                    511: ################################################
                    512: ################################################
                    513: 
                    514: ################################################
                    515: ################################################
1.89      matthew   516: { # Begin scope of table identifiers
1.57      matthew   517: 
                    518: my $current_course ='';
                    519: my $symb_table;
                    520: my $part_table;
                    521: my $student_table;
1.87      matthew   522: my $studentdata_table;
1.57      matthew   523: my $performance_table;
                    524: my $parameters_table;
1.89      matthew   525: my $fulldump_response_table;
                    526: my $fulldump_part_table;
                    527: my $fulldump_timestamp_table;
1.57      matthew   528: 
1.89      matthew   529: my @Tables;
1.57      matthew   530: ################################################
                    531: ################################################
                    532: 
                    533: =pod
                    534: 
                    535: =item &init_dbs()
                    536: 
                    537: Input: course id
                    538: 
                    539: Output: 0 on success, positive integer on error
                    540: 
                    541: This routine issues the calls to lonmysql to create the tables used to
                    542: store student data.
                    543: 
                    544: =cut
                    545: 
                    546: ################################################
                    547: ################################################
                    548: sub init_dbs {
                    549:     my $courseid = shift;
                    550:     &setup_table_names($courseid);
                    551:     #
1.73      matthew   552:     # Drop any of the existing tables
1.89      matthew   553:     foreach my $table (@Tables) {
1.73      matthew   554:         &Apache::lonmysql::drop_table($table);
                    555:     }
                    556:     #
1.57      matthew   557:     # Note - changes to this table must be reflected in the code that 
                    558:     # stores the data (calls &Apache::lonmysql::store_row with this table
                    559:     # id
                    560:     my $symb_table_def = {
                    561:         id => $symb_table,
                    562:         permanent => 'no',
                    563:         columns => [{ name => 'symb_id',
                    564:                       type => 'MEDIUMINT UNSIGNED',
                    565:                       restrictions => 'NOT NULL',
                    566:                       auto_inc     => 'yes', },
                    567:                     { name => 'symb',
                    568:                       type => 'MEDIUMTEXT',
                    569:                       restrictions => 'NOT NULL'},
                    570:                     ],
                    571:         'PRIMARY KEY' => ['symb_id'],
                    572:     };
                    573:     #
                    574:     my $part_table_def = {
                    575:         id => $part_table,
                    576:         permanent => 'no',
                    577:         columns => [{ name => 'part_id',
                    578:                       type => 'MEDIUMINT UNSIGNED',
                    579:                       restrictions => 'NOT NULL',
                    580:                       auto_inc     => 'yes', },
                    581:                     { name => 'part',
                    582:                       type => 'VARCHAR(100)',
                    583:                       restrictions => 'NOT NULL'},
                    584:                     ],
                    585:         'PRIMARY KEY' => ['part (100)'],
                    586:         'KEY' => [{ columns => ['part_id']},],
                    587:     };
                    588:     #
                    589:     my $student_table_def = {
                    590:         id => $student_table,
                    591:         permanent => 'no',
                    592:         columns => [{ name => 'student_id',
                    593:                       type => 'MEDIUMINT UNSIGNED',
                    594:                       restrictions => 'NOT NULL',
                    595:                       auto_inc     => 'yes', },
                    596:                     { name => 'student',
                    597:                       type => 'VARCHAR(100)',
                    598:                       restrictions => 'NOT NULL'},
1.85      matthew   599:                     { name => 'classification',
                    600:                       type => 'varchar(100)', },
1.57      matthew   601:                     ],
                    602:         'PRIMARY KEY' => ['student (100)'],
                    603:         'KEY' => [{ columns => ['student_id']},],
                    604:     };
                    605:     #
1.87      matthew   606:     my $studentdata_table_def = {
                    607:         id => $studentdata_table,
1.57      matthew   608:         permanent => 'no',
1.87      matthew   609:         columns => [{ name => 'student_id',
                    610:                       type => 'MEDIUMINT UNSIGNED',
1.57      matthew   611:                       restrictions => 'NOT NULL UNIQUE',},
                    612:                     { name => 'updatetime',
1.89      matthew   613:                       type => 'INT UNSIGNED'},
                    614:                     { name => 'fullupdatetime',
                    615:                       type => 'INT UNSIGNED'},
1.87      matthew   616:                     { name => 'section',
                    617:                       type => 'VARCHAR(100)'},
                    618:                     { name => 'classification',
                    619:                       type => 'VARCHAR(100)', },
1.57      matthew   620:                     ],
1.87      matthew   621:         'PRIMARY KEY' => ['student_id'],
1.57      matthew   622:     };
                    623:     #
                    624:     my $performance_table_def = {
                    625:         id => $performance_table,
                    626:         permanent => 'no',
                    627:         columns => [{ name => 'symb_id',
                    628:                       type => 'MEDIUMINT UNSIGNED',
                    629:                       restrictions => 'NOT NULL'  },
                    630:                     { name => 'student_id',
                    631:                       type => 'MEDIUMINT UNSIGNED',
                    632:                       restrictions => 'NOT NULL'  },
                    633:                     { name => 'part_id',
                    634:                       type => 'MEDIUMINT UNSIGNED',
                    635:                       restrictions => 'NOT NULL' },
1.73      matthew   636:                     { name => 'part',
                    637:                       type => 'VARCHAR(100)',
                    638:                       restrictions => 'NOT NULL'},                    
1.57      matthew   639:                     { name => 'solved',
                    640:                       type => 'TINYTEXT' },
                    641:                     { name => 'tries',
                    642:                       type => 'SMALLINT UNSIGNED' },
                    643:                     { name => 'awarded',
                    644:                       type => 'TINYTEXT' },
                    645:                     { name => 'award',
                    646:                       type => 'TINYTEXT' },
                    647:                     { name => 'awarddetail',
                    648:                       type => 'TINYTEXT' },
                    649:                     { name => 'timestamp',
                    650:                       type => 'INT UNSIGNED'},
                    651:                     ],
                    652:         'PRIMARY KEY' => ['symb_id','student_id','part_id'],
                    653:         'KEY' => [{ columns=>['student_id'] },
                    654:                   { columns=>['symb_id'] },],
                    655:     };
                    656:     #
1.89      matthew   657:     my $fulldump_part_table_def = {
                    658:         id => $fulldump_part_table,
                    659:         permanent => 'no',
                    660:         columns => [
                    661:                     { name => 'symb_id',
                    662:                       type => 'MEDIUMINT UNSIGNED',
                    663:                       restrictions => 'NOT NULL'  },
                    664:                     { name => 'part_id',
                    665:                       type => 'MEDIUMINT UNSIGNED',
                    666:                       restrictions => 'NOT NULL' },
                    667:                     { name => 'student_id',
                    668:                       type => 'MEDIUMINT UNSIGNED',
                    669:                       restrictions => 'NOT NULL'  },
                    670:                     { name => 'transaction',
                    671:                       type => 'MEDIUMINT UNSIGNED',
                    672:                       restrictions => 'NOT NULL' },
                    673:                     { name => 'tries',
                    674:                       type => 'SMALLINT UNSIGNED',
                    675:                       restrictions => 'NOT NULL' },
                    676:                     { name => 'award',
                    677:                       type => 'TINYTEXT' },
                    678:                     { name => 'awarded',
                    679:                       type => 'TINYTEXT' },
                    680:                     { name => 'previous',
                    681:                       type => 'SMALLINT UNSIGNED' },
                    682: #                    { name => 'regrader',
                    683: #                      type => 'TINYTEXT' },
                    684: #                    { name => 'afterduedate',
                    685: #                      type => 'TINYTEXT' },
                    686:                     ],
                    687:         'PRIMARY KEY' => ['symb_id','part_id','student_id','transaction'],
                    688:         'KEY' => [
                    689:                   { columns=>['symb_id'] },
                    690:                   { columns=>['part_id'] },
                    691:                   { columns=>['student_id'] },
                    692:                   ],
                    693:     };
                    694:     #
                    695:     my $fulldump_response_table_def = {
                    696:         id => $fulldump_response_table,
                    697:         permanent => 'no',
                    698:         columns => [
                    699:                     { name => 'symb_id',
                    700:                       type => 'MEDIUMINT UNSIGNED',
                    701:                       restrictions => 'NOT NULL'  },
                    702:                     { name => 'part_id',
                    703:                       type => 'MEDIUMINT UNSIGNED',
                    704:                       restrictions => 'NOT NULL' },
                    705:                     { name => 'response_id',
                    706:                       type => 'MEDIUMINT UNSIGNED',
                    707:                       restrictions => 'NOT NULL'  },
                    708:                     { name => 'student_id',
                    709:                       type => 'MEDIUMINT UNSIGNED',
                    710:                       restrictions => 'NOT NULL'  },
                    711:                     { name => 'transaction',
                    712:                       type => 'MEDIUMINT UNSIGNED',
                    713:                       restrictions => 'NOT NULL' },
                    714:                     { name => 'awarddetail',
                    715:                       type => 'TINYTEXT' },
                    716: #                    { name => 'message',
                    717: #                      type => 'CHAR' },
                    718:                     { name => 'response_specific',
                    719:                       type => 'TINYTEXT' },
                    720:                     { name => 'response_specific_value',
                    721:                       type => 'TINYTEXT' },
                    722:                     { name => 'submission',
                    723:                       type => 'TEXT'},
                    724:                     ],
                    725:             'PRIMARY KEY' => ['symb_id','part_id','response_id','student_id',
                    726:                               'transaction'],
                    727:             'KEY' => [
                    728:                       { columns=>['symb_id'] },
                    729:                       { columns=>['part_id','response_id'] },
                    730:                       { columns=>['student_id'] },
                    731:                       ],
                    732:     };
                    733:     my $fulldump_timestamp_table_def = {
                    734:         id => $fulldump_timestamp_table,
                    735:         permanent => 'no',
                    736:         columns => [
                    737:                     { name => 'symb_id',
                    738:                       type => 'MEDIUMINT UNSIGNED',
                    739:                       restrictions => 'NOT NULL'  },
                    740:                     { name => 'student_id',
                    741:                       type => 'MEDIUMINT UNSIGNED',
                    742:                       restrictions => 'NOT NULL'  },
                    743:                     { name => 'transaction',
                    744:                       type => 'MEDIUMINT UNSIGNED',
                    745:                       restrictions => 'NOT NULL' },
                    746:                     { name => 'timestamp',
                    747:                       type => 'INT UNSIGNED'},
                    748:                     ],
                    749:         'PRIMARY KEY' => ['symb_id','student_id','transaction'],
                    750:         'KEY' => [
                    751:                   { columns=>['symb_id'] },
                    752:                   { columns=>['student_id'] },
                    753:                   { columns=>['transaction'] },
                    754:                   ],
                    755:     };
                    756: 
                    757:     #
1.57      matthew   758:     my $parameters_table_def = {
                    759:         id => $parameters_table,
                    760:         permanent => 'no',
                    761:         columns => [{ name => 'symb_id',
                    762:                       type => 'MEDIUMINT UNSIGNED',
                    763:                       restrictions => 'NOT NULL'  },
                    764:                     { name => 'student_id',
                    765:                       type => 'MEDIUMINT UNSIGNED',
                    766:                       restrictions => 'NOT NULL'  },
                    767:                     { name => 'parameter',
                    768:                       type => 'TINYTEXT',
                    769:                       restrictions => 'NOT NULL'  },
                    770:                     { name => 'value',
                    771:                       type => 'MEDIUMTEXT' },
                    772:                     ],
                    773:         'PRIMARY KEY' => ['symb_id','student_id','parameter (255)'],
                    774:     };
                    775:     #
                    776:     # Create the tables
                    777:     my $tableid;
                    778:     $tableid = &Apache::lonmysql::create_table($symb_table_def);
                    779:     if (! defined($tableid)) {
                    780:         &Apache::lonnet::logthis("error creating symb_table: ".
                    781:                                  &Apache::lonmysql::get_error());
                    782:         return 1;
                    783:     }
                    784:     #
                    785:     $tableid = &Apache::lonmysql::create_table($part_table_def);
                    786:     if (! defined($tableid)) {
                    787:         &Apache::lonnet::logthis("error creating part_table: ".
                    788:                                  &Apache::lonmysql::get_error());
                    789:         return 2;
                    790:     }
                    791:     #
                    792:     $tableid = &Apache::lonmysql::create_table($student_table_def);
                    793:     if (! defined($tableid)) {
                    794:         &Apache::lonnet::logthis("error creating student_table: ".
                    795:                                  &Apache::lonmysql::get_error());
                    796:         return 3;
                    797:     }
                    798:     #
1.87      matthew   799:     $tableid = &Apache::lonmysql::create_table($studentdata_table_def);
1.57      matthew   800:     if (! defined($tableid)) {
1.87      matthew   801:         &Apache::lonnet::logthis("error creating studentdata_table: ".
1.57      matthew   802:                                  &Apache::lonmysql::get_error());
                    803:         return 4;
                    804:     }
                    805:     #
                    806:     $tableid = &Apache::lonmysql::create_table($performance_table_def);
                    807:     if (! defined($tableid)) {
                    808:         &Apache::lonnet::logthis("error creating preformance_table: ".
                    809:                                  &Apache::lonmysql::get_error());
                    810:         return 5;
                    811:     }
                    812:     #
                    813:     $tableid = &Apache::lonmysql::create_table($parameters_table_def);
                    814:     if (! defined($tableid)) {
                    815:         &Apache::lonnet::logthis("error creating parameters_table: ".
                    816:                                  &Apache::lonmysql::get_error());
                    817:         return 6;
                    818:     }
1.89      matthew   819:     #
                    820:     $tableid = &Apache::lonmysql::create_table($fulldump_part_table_def);
                    821:     if (! defined($tableid)) {
                    822:         &Apache::lonnet::logthis("error creating fulldump_part_table: ".
                    823:                                  &Apache::lonmysql::get_error());
                    824:         return 7;
                    825:     }
                    826:     #
                    827:     $tableid = &Apache::lonmysql::create_table($fulldump_response_table_def);
                    828:     if (! defined($tableid)) {
                    829:         &Apache::lonnet::logthis("error creating fulldump_response_table: ".
                    830:                                  &Apache::lonmysql::get_error());
                    831:         return 8;
                    832:     }
                    833:     $tableid = &Apache::lonmysql::create_table($fulldump_timestamp_table_def);
                    834:     if (! defined($tableid)) {
                    835:         &Apache::lonnet::logthis("error creating fulldump_timestamp_table: ".
                    836:                                  &Apache::lonmysql::get_error());
                    837:         return 9;
                    838:     }
1.57      matthew   839:     return 0;
1.70      matthew   840: }
                    841: 
                    842: ################################################
                    843: ################################################
                    844: 
                    845: =pod
                    846: 
                    847: =item &delete_caches()
                    848: 
                    849: =cut
                    850: 
                    851: ################################################
                    852: ################################################
                    853: sub delete_caches {
                    854:     my $courseid = shift;
                    855:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
                    856:     #
                    857:     &setup_table_names($courseid);
                    858:     #
                    859:     my $dbh = &Apache::lonmysql::get_dbh();
1.89      matthew   860:     foreach my $table (@Tables) {
1.70      matthew   861:         my $command = 'DROP TABLE '.$table.';';
                    862:         $dbh->do($command);
                    863:         if ($dbh->err) {
                    864:             &Apache::lonnet::logthis($command.' resulted in error: '.$dbh->errstr);
                    865:         }
                    866:     }
                    867:     return;
1.57      matthew   868: }
                    869: 
                    870: ################################################
                    871: ################################################
                    872: 
                    873: =pod
                    874: 
                    875: =item &get_part_id()
                    876: 
                    877: Get the MySQL id of a problem part string.
                    878: 
                    879: Input: $part
                    880: 
                    881: Output: undef on error, integer $part_id on success.
                    882: 
                    883: =item &get_part()
                    884: 
                    885: Get the string describing a part from the MySQL id of the problem part.
                    886: 
                    887: Input: $part_id
                    888: 
                    889: Output: undef on error, $part string on success.
                    890: 
                    891: =cut
                    892: 
                    893: ################################################
                    894: ################################################
                    895: 
1.61      matthew   896: my $have_read_part_table = 0;
1.57      matthew   897: my %ids_by_part;
                    898: my %parts_by_id;
                    899: 
                    900: sub get_part_id {
                    901:     my ($part) = @_;
1.61      matthew   902:     $part = 0 if (! defined($part));
                    903:     if (! $have_read_part_table) {
                    904:         my @Result = &Apache::lonmysql::get_rows($part_table);
                    905:         foreach (@Result) {
                    906:             $ids_by_part{$_->[1]}=$_->[0];
                    907:         }
                    908:         $have_read_part_table = 1;
                    909:     }
1.57      matthew   910:     if (! exists($ids_by_part{$part})) {
                    911:         &Apache::lonmysql::store_row($part_table,[undef,$part]);
                    912:         undef(%ids_by_part);
                    913:         my @Result = &Apache::lonmysql::get_rows($part_table);
                    914:         foreach (@Result) {
                    915:             $ids_by_part{$_->[1]}=$_->[0];
                    916:         }
                    917:     }
                    918:     return $ids_by_part{$part} if (exists($ids_by_part{$part}));
                    919:     return undef; # error
                    920: }
                    921: 
                    922: sub get_part {
                    923:     my ($part_id) = @_;
                    924:     if (! exists($parts_by_id{$part_id})  || 
                    925:         ! defined($parts_by_id{$part_id}) ||
                    926:         $parts_by_id{$part_id} eq '') {
                    927:         my @Result = &Apache::lonmysql::get_rows($part_table);
                    928:         foreach (@Result) {
                    929:             $parts_by_id{$_->[0]}=$_->[1];
                    930:         }
                    931:     }
                    932:     return $parts_by_id{$part_id} if(exists($parts_by_id{$part_id}));
                    933:     return undef; # error
                    934: }
                    935: 
                    936: ################################################
                    937: ################################################
                    938: 
                    939: =pod
                    940: 
                    941: =item &get_symb_id()
                    942: 
                    943: Get the MySQL id of a symb.
                    944: 
                    945: Input: $symb
                    946: 
                    947: Output: undef on error, integer $symb_id on success.
                    948: 
                    949: =item &get_symb()
                    950: 
                    951: Get the symb associated with a MySQL symb_id.
                    952: 
                    953: Input: $symb_id
                    954: 
                    955: Output: undef on error, $symb on success.
                    956: 
                    957: =cut
                    958: 
                    959: ################################################
                    960: ################################################
                    961: 
1.61      matthew   962: my $have_read_symb_table = 0;
1.57      matthew   963: my %ids_by_symb;
                    964: my %symbs_by_id;
                    965: 
                    966: sub get_symb_id {
                    967:     my ($symb) = @_;
1.61      matthew   968:     if (! $have_read_symb_table) {
                    969:         my @Result = &Apache::lonmysql::get_rows($symb_table);
                    970:         foreach (@Result) {
                    971:             $ids_by_symb{$_->[1]}=$_->[0];
                    972:         }
                    973:         $have_read_symb_table = 1;
                    974:     }
1.57      matthew   975:     if (! exists($ids_by_symb{$symb})) {
                    976:         &Apache::lonmysql::store_row($symb_table,[undef,$symb]);
                    977:         undef(%ids_by_symb);
                    978:         my @Result = &Apache::lonmysql::get_rows($symb_table);
                    979:         foreach (@Result) {
                    980:             $ids_by_symb{$_->[1]}=$_->[0];
                    981:         }
                    982:     }
                    983:     return $ids_by_symb{$symb} if(exists( $ids_by_symb{$symb}));
                    984:     return undef; # error
                    985: }
                    986: 
                    987: sub get_symb {
                    988:     my ($symb_id) = @_;
                    989:     if (! exists($symbs_by_id{$symb_id})  || 
                    990:         ! defined($symbs_by_id{$symb_id}) ||
                    991:         $symbs_by_id{$symb_id} eq '') {
                    992:         my @Result = &Apache::lonmysql::get_rows($symb_table);
                    993:         foreach (@Result) {
                    994:             $symbs_by_id{$_->[0]}=$_->[1];
                    995:         }
                    996:     }
                    997:     return $symbs_by_id{$symb_id} if(exists( $symbs_by_id{$symb_id}));
                    998:     return undef; # error
                    999: }
                   1000: 
                   1001: ################################################
                   1002: ################################################
                   1003: 
                   1004: =pod
                   1005: 
                   1006: =item &get_student_id()
                   1007: 
                   1008: Get the MySQL id of a student.
                   1009: 
                   1010: Input: $sname, $dom
                   1011: 
                   1012: Output: undef on error, integer $student_id on success.
                   1013: 
                   1014: =item &get_student()
                   1015: 
                   1016: Get student username:domain associated with the MySQL student_id.
                   1017: 
                   1018: Input: $student_id
                   1019: 
                   1020: Output: undef on error, string $student (username:domain) on success.
                   1021: 
                   1022: =cut
                   1023: 
                   1024: ################################################
                   1025: ################################################
                   1026: 
1.61      matthew  1027: my $have_read_student_table = 0;
1.57      matthew  1028: my %ids_by_student;
                   1029: my %students_by_id;
                   1030: 
                   1031: sub get_student_id {
                   1032:     my ($sname,$sdom) = @_;
                   1033:     my $student = $sname.':'.$sdom;
1.61      matthew  1034:     if (! $have_read_student_table) {
                   1035:         my @Result = &Apache::lonmysql::get_rows($student_table);
                   1036:         foreach (@Result) {
                   1037:             $ids_by_student{$_->[1]}=$_->[0];
                   1038:         }
                   1039:         $have_read_student_table = 1;
                   1040:     }
1.57      matthew  1041:     if (! exists($ids_by_student{$student})) {
1.106   ! matthew  1042:         &Apache::lonmysql::store_row($student_table,
        !          1043:                                      [undef,$student,undef]);
1.57      matthew  1044:         undef(%ids_by_student);
                   1045:         my @Result = &Apache::lonmysql::get_rows($student_table);
                   1046:         foreach (@Result) {
                   1047:             $ids_by_student{$_->[1]}=$_->[0];
                   1048:         }
                   1049:     }
                   1050:     return $ids_by_student{$student} if(exists( $ids_by_student{$student}));
                   1051:     return undef; # error
                   1052: }
                   1053: 
                   1054: sub get_student {
                   1055:     my ($student_id) = @_;
                   1056:     if (! exists($students_by_id{$student_id})  || 
                   1057:         ! defined($students_by_id{$student_id}) ||
                   1058:         $students_by_id{$student_id} eq '') {
                   1059:         my @Result = &Apache::lonmysql::get_rows($student_table);
                   1060:         foreach (@Result) {
                   1061:             $students_by_id{$_->[0]}=$_->[1];
                   1062:         }
                   1063:     }
                   1064:     return $students_by_id{$student_id} if(exists($students_by_id{$student_id}));
                   1065:     return undef; # error
                   1066: }
1.99      matthew  1067: 
                   1068: ################################################
                   1069: ################################################
                   1070: 
                   1071: =pod
                   1072: 
                   1073: =item &clear_internal_caches()
                   1074: 
                   1075: Causes the internal caches used in get_student_id, get_student,
                   1076: get_symb_id, get_symb, get_part_id, and get_part to be undef'd.
                   1077: 
                   1078: Needs to be called before the first operation with the MySQL database
                   1079: for a given Apache request.
                   1080: 
                   1081: =cut
                   1082: 
                   1083: ################################################
                   1084: ################################################
                   1085: sub clear_internal_caches {
                   1086:     $have_read_part_table = 0;
                   1087:     undef(%ids_by_part);
                   1088:     undef(%parts_by_id);
                   1089:     $have_read_symb_table = 0;
                   1090:     undef(%ids_by_symb);
                   1091:     undef(%symbs_by_id);
                   1092:     $have_read_student_table = 0;
                   1093:     undef(%ids_by_student);
                   1094:     undef(%students_by_id);
                   1095: }
                   1096: 
1.57      matthew  1097: 
                   1098: ################################################
                   1099: ################################################
                   1100: 
                   1101: =pod
                   1102: 
1.89      matthew  1103: =item &update_full_student_data($sname,$sdom,$courseid)
                   1104: 
                   1105: Does a lonnet::dump on a student to populate the courses tables.
                   1106: 
                   1107: Input: $sname, $sdom, $courseid
                   1108: 
                   1109: Output: $returnstatus
                   1110: 
                   1111: $returnstatus is a string describing any errors that occured.  'okay' is the
                   1112: default.
                   1113: 
                   1114: This subroutine loads a students data using lonnet::dump and inserts
                   1115: it into the MySQL database.  The inserts are done on three tables, 
                   1116: $fulldump_response_table, $fulldump_part_table, and $fulldump_timestamp_table.
                   1117: The INSERT calls are made directly by this subroutine, not through lonmysql 
                   1118: because we do a 'bulk'insert which takes advantage of MySQLs non-SQL 
                   1119: compliant INSERT command to insert multiple rows at a time.  
                   1120: If anything has gone wrong during this process, $returnstatus is updated with 
                   1121: a description of the error.
                   1122: 
                   1123: Once the "fulldump" tables are updated, the tables used for chart and
                   1124: spreadsheet (which hold only the current state of the student on their
                   1125: homework, not historical data) are updated.  If all updates have occured 
                   1126: successfully, the studentdata table is updated to reflect the time of the
                   1127: update.
                   1128: 
                   1129: Notice we do not insert the data and immediately query it.  This means it
                   1130: is possible for there to be data returned this first time that is not 
                   1131: available the second time.  CYA.
                   1132: 
                   1133: =cut
                   1134: 
                   1135: ################################################
                   1136: ################################################
                   1137: sub update_full_student_data {
                   1138:     my ($sname,$sdom,$courseid) = @_;
                   1139:     #
                   1140:     # Set up database names
                   1141:     &setup_table_names($courseid);
                   1142:     #
                   1143:     my $student_id = &get_student_id($sname,$sdom);
                   1144:     my $student = $sname.':'.$sdom;
                   1145:     #
                   1146:     my $returnstatus = 'okay';
                   1147:     #
                   1148:     # Download students data
                   1149:     my $time_of_retrieval = time;
                   1150:     my @tmp = &Apache::lonnet::dump($courseid,$sdom,$sname);
                   1151:     if (@tmp && $tmp[0] =~ /^error/) {
                   1152:         $returnstatus = 'error retrieving full student data';
                   1153:         return $returnstatus;
                   1154:     } elsif (! @tmp) {
                   1155:         $returnstatus = 'okay: no student data';
                   1156:         return $returnstatus;
                   1157:     }
                   1158:     my %studentdata = @tmp;
                   1159:     #
                   1160:     # Get database handle and clean out the tables 
                   1161:     my $dbh = &Apache::lonmysql::get_dbh();
                   1162:     $dbh->do('DELETE FROM '.$fulldump_response_table.' WHERE student_id='.
                   1163:              $student_id);
                   1164:     $dbh->do('DELETE FROM '.$fulldump_part_table.' WHERE student_id='.
                   1165:              $student_id);
                   1166:     $dbh->do('DELETE FROM '.$fulldump_timestamp_table.' WHERE student_id='.
                   1167:              $student_id);
                   1168:     #
                   1169:     # Parse and store the data into a form we can handle
                   1170:     my $partdata;
                   1171:     my $respdata;
                   1172:     while (my ($key,$value) = each(%studentdata)) {
                   1173:         next if ($key =~ /^(\d+):(resource$|subnum$|keys:)/);
                   1174:         my ($transaction,$symb,$parameter) = split(':',$key);
                   1175:         my $symb_id = &get_symb_id($symb);
                   1176:         if ($parameter eq 'timestamp') {
                   1177:             # We can deal with 'timestamp' right away
                   1178:             my @timestamp_storage = ($symb_id,$student_id,
                   1179:                                      $transaction,$value);
1.98      matthew  1180:             my $store_command = 'INSERT IGNORE INTO '.$fulldump_timestamp_table.
1.89      matthew  1181:                 " VALUES ('".join("','",@timestamp_storage)."');";
                   1182:             $dbh->do($store_command);
                   1183:             if ($dbh->err()) {
                   1184:                 &Apache::lonnet::logthis('unable to execute '.$store_command);
                   1185:                 &Apache::lonnet::logthis($dbh->errstr());
                   1186:             }
                   1187:             next;
                   1188:         } elsif ($parameter eq 'version') {
                   1189:             next;
1.90      matthew  1190:         } elsif ($parameter =~ /^resource\.(.*)\.(tries|
                   1191:                                                   award|
                   1192:                                                   awarded|
                   1193:                                                   previous|
                   1194:                                                   solved|
                   1195:                                                   awarddetail|
                   1196:                                                   submission|
                   1197:                                                   submissiongrading|
                   1198:                                                   molecule)\s*$/x){
1.89      matthew  1199:             # we do not have enough information to store an 
                   1200:             # entire row, so we save it up until later.
                   1201:             my ($part_and_resp_id,$field) = ($1,$2);
                   1202:             my ($part,$part_id,$resp,$resp_id);
                   1203:             if ($part_and_resp_id =~ /\./) {
                   1204:                 ($part,$resp) = split(/\./,$part_and_resp_id);
                   1205:                 $part_id = &get_part_id($part);
                   1206:                 $resp_id = &get_part_id($resp);
                   1207:             } else {
                   1208:                 $part_id = &get_part_id($part_and_resp_id);
                   1209:             }
1.90      matthew  1210:             # Deal with part specific data
1.89      matthew  1211:             if ($field =~ /^(tries|award|awarded|previous)$/) {
                   1212:                 $partdata->{$symb_id}->{$part_id}->{$transaction}->{$field}=$value;
                   1213:             }
1.90      matthew  1214:             # deal with response specific data
1.89      matthew  1215:             if (defined($resp_id) &&
1.100     matthew  1216:                 $field =~ /^(awarddetail|
1.90      matthew  1217:                              submission|
                   1218:                              submissiongrading|
                   1219:                              molecule)$/x) {
1.89      matthew  1220:                 if ($field eq 'submission') {
                   1221:                     # We have to be careful with user supplied input.
                   1222:                     # most of the time we are okay because it is escaped.
                   1223:                     # However, there is one wrinkle: submissions which end in
                   1224:                     # and odd number of '\' cause insert errors to occur.  
                   1225:                     # Best trap this somehow...
1.102     matthew  1226:                     $value =~ s/\'/\\\'/g;
1.89      matthew  1227:                     my ($offensive_string) = ($value =~ /(\\+)$/);
                   1228:                     if (length($offensive_string) % 2) {
                   1229:                         $value =~ s/\\$/\\\\/;
                   1230:                     }
                   1231:                 }
1.90      matthew  1232:                 if ($field eq 'submissiongrading' || 
                   1233:                     $field eq 'molecule') {
                   1234:                     $respdata->{$symb_id}->{$part_id}->{$resp_id}->{$transaction}->{'response_specific'}=$field;
                   1235:                     $respdata->{$symb_id}->{$part_id}->{$resp_id}->{$transaction}->{'response_specific_value'}=$value;
                   1236:                 } else {
                   1237:                     $respdata->{$symb_id}->{$part_id}->{$resp_id}->{$transaction}->{$field}=$value;
                   1238:                 }
1.89      matthew  1239:             }
                   1240:         }
                   1241:     }
                   1242:     ##
                   1243:     ## Store the part data
1.98      matthew  1244:     my $store_command = 'INSERT IGNORE INTO '.$fulldump_part_table.
1.89      matthew  1245:         ' VALUES '."\n";
                   1246:     my $store_rows = 0;
                   1247:     while (my ($symb_id,$hash1) = each (%$partdata)) {
                   1248:         while (my ($part_id,$hash2) = each (%$hash1)) {
                   1249:             while (my ($transaction,$data) = each (%$hash2)) {
                   1250:                 $store_command .= "('".join("','",$symb_id,$part_id,
                   1251:                                             $student_id,
                   1252:                                             $transaction,
1.101     matthew  1253:                                             $data->{'tries'},
1.89      matthew  1254:                                             $data->{'award'},
                   1255:                                             $data->{'awarded'},
                   1256:                                             $data->{'previous'})."'),";
                   1257:                 $store_rows++;
                   1258:             }
                   1259:         }
                   1260:     }
                   1261:     if ($store_rows) {
                   1262:         chop($store_command);
                   1263:         $dbh->do($store_command);
                   1264:         if ($dbh->err) {
                   1265:             $returnstatus = 'error storing part data';
                   1266:             &Apache::lonnet::logthis('insert error '.$dbh->errstr());
                   1267:             &Apache::lonnet::logthis("While attempting\n".$store_command);
                   1268:         }
                   1269:     }
                   1270:     ##
                   1271:     ## Store the response data
1.98      matthew  1272:     $store_command = 'INSERT IGNORE INTO '.$fulldump_response_table.
1.89      matthew  1273:         ' VALUES '."\n";
                   1274:     $store_rows = 0;
                   1275:     while (my ($symb_id,$hash1) = each (%$respdata)) {
                   1276:         while (my ($part_id,$hash2) = each (%$hash1)) {
                   1277:             while (my ($resp_id,$hash3) = each (%$hash2)) {
                   1278:                 while (my ($transaction,$data) = each (%$hash3)) {
                   1279:                     $store_command .= "('".join("','",$symb_id,$part_id,
                   1280:                                                 $resp_id,$student_id,
                   1281:                                                 $transaction,
                   1282:                                                 $data->{'awarddetail'},
1.90      matthew  1283:                                                 $data->{'response_specific'},
                   1284:                                                 $data->{'response_specific_value'},
1.89      matthew  1285:                                                 $data->{'submission'})."'),";
                   1286:                     $store_rows++;
                   1287:                 }
                   1288:             }
                   1289:         }
                   1290:     }
                   1291:     if ($store_rows) {
                   1292:         chop($store_command);
                   1293:         $dbh->do($store_command);
                   1294:         if ($dbh->err) {
                   1295:             $returnstatus = 'error storing response data';
                   1296:             &Apache::lonnet::logthis('insert error '.$dbh->errstr());
                   1297:             &Apache::lonnet::logthis("While attempting\n".$store_command);
                   1298:         }
                   1299:     }
                   1300:     ##
                   1301:     ## Update the students "current" data in the performance 
                   1302:     ## and parameters tables.
                   1303:     my ($status,undef) = &store_student_data
                   1304:         ($sname,$sdom,$courseid,
                   1305:          &Apache::lonnet::convert_dump_to_currentdump(\%studentdata));
                   1306:     if ($returnstatus eq 'okay' && $status ne 'okay') {
                   1307:         $returnstatus = 'error storing current data:'.$status;
                   1308:     } elsif ($status ne 'okay') {
                   1309:         $returnstatus .= ' error storing current data:'.$status;
                   1310:     }        
                   1311:     ##
                   1312:     ## Update the students time......
                   1313:     if ($returnstatus eq 'okay') {
                   1314:         &Apache::lonmysql::replace_row
                   1315:             ($studentdata_table,
                   1316:              [$student_id,$time_of_retrieval,$time_of_retrieval,undef,undef]);
                   1317:     }
                   1318:     return $returnstatus;
                   1319: }
                   1320: 
                   1321: ################################################
                   1322: ################################################
                   1323: 
                   1324: =pod
                   1325: 
1.57      matthew  1326: =item &update_student_data()
                   1327: 
                   1328: Input: $sname, $sdom, $courseid
                   1329: 
                   1330: Output: $returnstatus, \%student_data
                   1331: 
                   1332: $returnstatus is a string describing any errors that occured.  'okay' is the
                   1333: default.
                   1334: \%student_data is the data returned by a call to lonnet::currentdump.
                   1335: 
                   1336: This subroutine loads a students data using lonnet::currentdump and inserts
                   1337: it into the MySQL database.  The inserts are done on two tables, 
                   1338: $performance_table and $parameters_table.  $parameters_table holds the data 
                   1339: that is not included in $performance_table.  See the description of 
                   1340: $performance_table elsewhere in this file.  The INSERT calls are made
                   1341: directly by this subroutine, not through lonmysql because we do a 'bulk'
                   1342: insert which takes advantage of MySQLs non-SQL compliant INSERT command to 
                   1343: insert multiple rows at a time.  If anything has gone wrong during this
                   1344: process, $returnstatus is updated with a description of the error and
                   1345: \%student_data is returned.  
                   1346: 
                   1347: Notice we do not insert the data and immediately query it.  This means it
                   1348: is possible for there to be data returned this first time that is not 
                   1349: available the second time.  CYA.
                   1350: 
                   1351: =cut
                   1352: 
                   1353: ################################################
                   1354: ################################################
                   1355: sub update_student_data {
                   1356:     my ($sname,$sdom,$courseid) = @_;
                   1357:     #
1.60      matthew  1358:     # Set up database names
                   1359:     &setup_table_names($courseid);
                   1360:     #
1.57      matthew  1361:     my $student_id = &get_student_id($sname,$sdom);
                   1362:     my $student = $sname.':'.$sdom;
                   1363:     #
                   1364:     my $returnstatus = 'okay';
                   1365:     #
                   1366:     # Download students data
                   1367:     my $time_of_retrieval = time;
                   1368:     my @tmp = &Apache::lonnet::currentdump($courseid,$sdom,$sname);
                   1369:     if ((scalar(@tmp) > 0) && ($tmp[0] =~ /^error:/)) {
                   1370:         &Apache::lonnet::logthis('error getting data for '.
                   1371:                                  $sname.':'.$sdom.' in course '.$courseid.
                   1372:                                  ':'.$tmp[0]);
                   1373:         $returnstatus = 'error getting data';
1.79      matthew  1374:         return ($returnstatus,undef);
1.57      matthew  1375:     }
                   1376:     if (scalar(@tmp) < 1) {
                   1377:         return ('no data',undef);
                   1378:     }
                   1379:     my %student_data = @tmp;
1.89      matthew  1380:     my @Results = &store_student_data($sname,$sdom,$courseid,\%student_data);
                   1381:     #
                   1382:     # Set the students update time
1.96      matthew  1383:     if ($Results[0] eq 'okay') {
1.95      matthew  1384:         &Apache::lonmysql::replace_row($studentdata_table,
1.89      matthew  1385:                          [$student_id,$time_of_retrieval,undef,undef,undef]);
1.95      matthew  1386:     }
1.89      matthew  1387:     #
                   1388:     return @Results;
                   1389: }
                   1390: 
                   1391: sub store_student_data {
                   1392:     my ($sname,$sdom,$courseid,$student_data) = @_;
                   1393:     #
                   1394:     my $student_id = &get_student_id($sname,$sdom);
                   1395:     my $student = $sname.':'.$sdom;
                   1396:     #
                   1397:     my $returnstatus = 'okay';
1.57      matthew  1398:     #
                   1399:     # Remove all of the students data from the table
1.60      matthew  1400:     my $dbh = &Apache::lonmysql::get_dbh();
                   1401:     $dbh->do('DELETE FROM '.$performance_table.' WHERE student_id='.
                   1402:              $student_id);
                   1403:     $dbh->do('DELETE FROM '.$parameters_table.' WHERE student_id='.
                   1404:              $student_id);
1.57      matthew  1405:     #
                   1406:     # Store away the data
                   1407:     #
                   1408:     my $starttime = Time::HiRes::time;
                   1409:     my $elapsed = 0;
                   1410:     my $rows_stored;
1.98      matthew  1411:     my $store_parameters_command  = 'INSERT IGNORE INTO '.$parameters_table.
1.60      matthew  1412:         ' VALUES '."\n";
1.61      matthew  1413:     my $num_parameters = 0;
1.98      matthew  1414:     my $store_performance_command = 'INSERT IGNORE INTO '.$performance_table.
1.60      matthew  1415:         ' VALUES '."\n";
1.79      matthew  1416:     return ('error',undef) if (! defined($dbh));
1.89      matthew  1417:     while (my ($current_symb,$param_hash) = each(%{$student_data})) {
1.57      matthew  1418:         #
                   1419:         # make sure the symb is set up properly
                   1420:         my $symb_id = &get_symb_id($current_symb);
                   1421:         #
                   1422:         # Load data into the tables
1.63      matthew  1423:         while (my ($parameter,$value) = each(%$param_hash)) {
1.57      matthew  1424:             my $newstring;
1.63      matthew  1425:             if ($parameter !~ /(timestamp|resource\.(.*)\.(solved|tries|awarded|award|awarddetail|previous))/) {
1.57      matthew  1426:                 $newstring = "('".join("','",
                   1427:                                        $symb_id,$student_id,
1.69      matthew  1428:                                        $parameter)."',".
                   1429:                                            $dbh->quote($value)."),\n";
1.61      matthew  1430:                 $num_parameters ++;
1.57      matthew  1431:                 if ($newstring !~ /''/) {
                   1432:                     $store_parameters_command .= $newstring;
                   1433:                     $rows_stored++;
                   1434:                 }
                   1435:             }
                   1436:             next if ($parameter !~ /^resource\.(.*)\.solved$/);
                   1437:             #
                   1438:             my $part = $1;
                   1439:             my $part_id = &get_part_id($part);
                   1440:             next if (!defined($part_id));
                   1441:             my $solved  = $value;
                   1442:             my $tries   = $param_hash->{'resource.'.$part.'.tries'};
                   1443:             my $awarded = $param_hash->{'resource.'.$part.'.awarded'};
                   1444:             my $award   = $param_hash->{'resource.'.$part.'.award'};
                   1445:             my $awarddetail = $param_hash->{'resource.'.$part.'.awarddetail'};
                   1446:             my $timestamp = $param_hash->{'timestamp'};
1.60      matthew  1447:             #
1.74      matthew  1448:             $solved      = '' if (! defined($solved));
1.57      matthew  1449:             $tries       = '' if (! defined($tries));
                   1450:             $awarded     = '' if (! defined($awarded));
                   1451:             $award       = '' if (! defined($award));
                   1452:             $awarddetail = '' if (! defined($awarddetail));
1.73      matthew  1453:             $newstring = "('".join("','",$symb_id,$student_id,$part_id,$part,
1.57      matthew  1454:                                    $solved,$tries,$awarded,$award,
1.63      matthew  1455:                                    $awarddetail,$timestamp)."'),\n";
1.57      matthew  1456:             $store_performance_command .= $newstring;
                   1457:             $rows_stored++;
                   1458:         }
                   1459:     }
                   1460:     chop $store_parameters_command;
1.60      matthew  1461:     chop $store_parameters_command;
                   1462:     chop $store_performance_command;
1.57      matthew  1463:     chop $store_performance_command;
                   1464:     my $start = Time::HiRes::time;
1.94      matthew  1465:     $dbh->do($store_performance_command);
                   1466:     if ($dbh->err()) {
                   1467:         &Apache::lonnet::logthis(' bigass insert error:'.$dbh->errstr());
                   1468:         &Apache::lonnet::logthis('command = '.$store_performance_command);
                   1469:         $returnstatus = 'error: unable to insert performance into database';
                   1470:         return ($returnstatus,$student_data);
                   1471:     }
1.61      matthew  1472:     $dbh->do($store_parameters_command) if ($num_parameters>0);
1.57      matthew  1473:     if ($dbh->err()) {
                   1474:         &Apache::lonnet::logthis(' bigass insert error:'.$dbh->errstr());
1.61      matthew  1475:         &Apache::lonnet::logthis('command = '.$store_parameters_command);
1.87      matthew  1476:         &Apache::lonnet::logthis('rows_stored = '.$rows_stored);
                   1477:         &Apache::lonnet::logthis('student_id = '.$student_id);
1.57      matthew  1478:         $returnstatus = 'error: unable to insert parameters into database';
1.89      matthew  1479:         return ($returnstatus,$student_data);
1.57      matthew  1480:     }
                   1481:     $elapsed += Time::HiRes::time - $start;
1.89      matthew  1482:     return ($returnstatus,$student_data);
1.57      matthew  1483: }
                   1484: 
1.89      matthew  1485: ######################################
                   1486: ######################################
1.57      matthew  1487: 
                   1488: =pod
                   1489: 
1.89      matthew  1490: =item &ensure_tables_are_set_up($courseid)
1.57      matthew  1491: 
1.89      matthew  1492: Checks to be sure the MySQL tables for the given class are set up.
                   1493: If $courseid is omitted it will be obtained from the environment.
1.57      matthew  1494: 
1.89      matthew  1495: Returns nothing on success and 'error' on failure
1.57      matthew  1496: 
                   1497: =cut
                   1498: 
1.89      matthew  1499: ######################################
                   1500: ######################################
                   1501: sub ensure_tables_are_set_up {
                   1502:     my ($courseid) = @_;
1.61      matthew  1503:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
                   1504:     # 
                   1505:     # Clean out package variables
1.57      matthew  1506:     &setup_table_names($courseid);
                   1507:     #
                   1508:     # if the tables do not exist, make them
                   1509:     my @CurrentTable = &Apache::lonmysql::tables_in_db();
1.87      matthew  1510:     my ($found_symb,$found_student,$found_part,$found_studentdata,
1.89      matthew  1511:         $found_performance,$found_parameters,$found_fulldump_part,
                   1512:         $found_fulldump_response,$found_fulldump_timestamp);
1.57      matthew  1513:     foreach (@CurrentTable) {
                   1514:         $found_symb        = 1 if ($_ eq $symb_table);
                   1515:         $found_student     = 1 if ($_ eq $student_table);
                   1516:         $found_part        = 1 if ($_ eq $part_table);
1.87      matthew  1517:         $found_studentdata = 1 if ($_ eq $studentdata_table);
1.57      matthew  1518:         $found_performance = 1 if ($_ eq $performance_table);
                   1519:         $found_parameters  = 1 if ($_ eq $parameters_table);
1.89      matthew  1520:         $found_fulldump_part      = 1 if ($_ eq $fulldump_part_table);
                   1521:         $found_fulldump_response  = 1 if ($_ eq $fulldump_response_table);
                   1522:         $found_fulldump_timestamp = 1 if ($_ eq $fulldump_timestamp_table);
1.57      matthew  1523:     }
1.87      matthew  1524:     if (!$found_symb        || !$found_studentdata || 
1.57      matthew  1525:         !$found_student     || !$found_part   ||
1.89      matthew  1526:         !$found_performance || !$found_parameters ||
                   1527:         !$found_fulldump_part || !$found_fulldump_response ||
                   1528:         !$found_fulldump_timestamp ) {
1.57      matthew  1529:         if (&init_dbs($courseid)) {
1.89      matthew  1530:             return 'error';
1.57      matthew  1531:         }
                   1532:     }
1.89      matthew  1533: }
                   1534: 
                   1535: ################################################
                   1536: ################################################
                   1537: 
                   1538: =pod
                   1539: 
                   1540: =item &ensure_current_data()
                   1541: 
                   1542: Input: $sname, $sdom, $courseid
                   1543: 
                   1544: Output: $status, $data
                   1545: 
                   1546: This routine ensures the data for a given student is up to date.
                   1547: The $studentdata_table is queried to determine the time of the last update.  
                   1548: If the students data is out of date, &update_student_data() is called.  
                   1549: The return values from the call to &update_student_data() are returned.
                   1550: 
                   1551: =cut
                   1552: 
                   1553: ################################################
                   1554: ################################################
                   1555: sub ensure_current_data {
                   1556:     my ($sname,$sdom,$courseid) = @_;
                   1557:     my $status = 'okay';   # return value
                   1558:     #
                   1559:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
                   1560:     &ensure_tables_are_set_up($courseid);
1.57      matthew  1561:     #
                   1562:     # Get the update time for the user
                   1563:     my $updatetime = 0;
1.60      matthew  1564:     my $modifiedtime = &Apache::lonnet::GetFileTimestamp
                   1565:         ($sdom,$sname,$courseid.'.db',
                   1566:          $Apache::lonnet::perlvar{'lonUsersDir'});
1.57      matthew  1567:     #
1.87      matthew  1568:     my $student_id = &get_student_id($sname,$sdom);
                   1569:     my @Result = &Apache::lonmysql::get_rows($studentdata_table,
                   1570:                                              "student_id ='$student_id'");
1.57      matthew  1571:     my $data = undef;
                   1572:     if (@Result) {
                   1573:         $updatetime = $Result[0]->[1];
                   1574:     }
                   1575:     if ($modifiedtime > $updatetime) {
                   1576:         ($status,$data) = &update_student_data($sname,$sdom,$courseid);
                   1577:     }
                   1578:     return ($status,$data);
                   1579: }
                   1580: 
                   1581: ################################################
                   1582: ################################################
                   1583: 
                   1584: =pod
                   1585: 
1.89      matthew  1586: =item &ensure_current_full_data($sname,$sdom,$courseid)
                   1587: 
                   1588: Input: $sname, $sdom, $courseid
                   1589: 
                   1590: Output: $status
                   1591: 
                   1592: This routine ensures the fulldata (the data from a lonnet::dump, not a
                   1593: lonnet::currentdump) for a given student is up to date.
                   1594: The $studentdata_table is queried to determine the time of the last update.  
                   1595: If the students fulldata is out of date, &update_full_student_data() is
                   1596: called.  
                   1597: 
                   1598: The return value from the call to &update_full_student_data() is returned.
                   1599: 
                   1600: =cut
                   1601: 
                   1602: ################################################
                   1603: ################################################
                   1604: sub ensure_current_full_data {
                   1605:     my ($sname,$sdom,$courseid) = @_;
                   1606:     my $status = 'okay';   # return value
                   1607:     #
                   1608:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
                   1609:     &ensure_tables_are_set_up($courseid);
                   1610:     #
                   1611:     # Get the update time for the user
                   1612:     my $modifiedtime = &Apache::lonnet::GetFileTimestamp
                   1613:         ($sdom,$sname,$courseid.'.db',
                   1614:          $Apache::lonnet::perlvar{'lonUsersDir'});
                   1615:     #
                   1616:     my $student_id = &get_student_id($sname,$sdom);
                   1617:     my @Result = &Apache::lonmysql::get_rows($studentdata_table,
                   1618:                                              "student_id ='$student_id'");
                   1619:     my $updatetime;
                   1620:     if (@Result && ref($Result[0]) eq 'ARRAY') {
                   1621:         $updatetime = $Result[0]->[2];
                   1622:     }
                   1623:     if (! defined($updatetime) || $modifiedtime > $updatetime) {
                   1624:         $status = &update_full_student_data($sname,$sdom,$courseid);
                   1625:     }
                   1626:     return $status;
                   1627: }
                   1628: 
                   1629: ################################################
                   1630: ################################################
                   1631: 
                   1632: =pod
                   1633: 
1.57      matthew  1634: =item &get_student_data_from_performance_cache()
                   1635: 
                   1636: Input: $sname, $sdom, $symb, $courseid
                   1637: 
                   1638: Output: hash reference containing the data for the given student.
                   1639: If $symb is undef, all the students data is returned.
                   1640: 
                   1641: This routine is the heart of the local caching system.  See the description
                   1642: of $performance_table, $symb_table, $student_table, and $part_table.  The
                   1643: main task is building the MySQL request.  The tables appear in the request
                   1644: in the order in which they should be parsed by MySQL.  When searching
                   1645: on a student the $student_table is used to locate the 'student_id'.  All
                   1646: rows in $performance_table which have a matching 'student_id' are returned,
                   1647: with data from $part_table and $symb_table which match the entries in
                   1648: $performance_table, 'part_id' and 'symb_id'.  When searching on a symb,
                   1649: the $symb_table is processed first, with matching rows grabbed from 
                   1650: $performance_table and filled in from $part_table and $student_table in
                   1651: that order.  
                   1652: 
                   1653: Running 'EXPLAIN ' on the 'SELECT' statements generated can be quite 
                   1654: interesting, especially if you play with the order the tables are listed.  
                   1655: 
                   1656: =cut
                   1657: 
                   1658: ################################################
                   1659: ################################################
                   1660: sub get_student_data_from_performance_cache {
                   1661:     my ($sname,$sdom,$symb,$courseid)=@_;
                   1662:     my $student = $sname.':'.$sdom if (defined($sname) && defined($sdom));
1.61      matthew  1663:     &setup_table_names($courseid);
1.57      matthew  1664:     #
                   1665:     # Return hash
                   1666:     my $studentdata;
                   1667:     #
                   1668:     my $dbh = &Apache::lonmysql::get_dbh();
                   1669:     my $request = "SELECT ".
1.73      matthew  1670:         "d.symb,a.part,a.solved,a.tries,a.awarded,a.award,a.awarddetail,".
1.63      matthew  1671:             "a.timestamp ";
1.57      matthew  1672:     if (defined($student)) {
                   1673:         $request .= "FROM $student_table AS b ".
                   1674:             "LEFT JOIN $performance_table AS a ON b.student_id=a.student_id ".
1.73      matthew  1675: #            "LEFT JOIN $part_table AS c ON c.part_id = a.part_id ".
1.57      matthew  1676:             "LEFT JOIN $symb_table AS d ON d.symb_id = a.symb_id ".
                   1677:                 "WHERE student='$student'";
                   1678:         if (defined($symb) && $symb ne '') {
1.67      matthew  1679:             $request .= " AND d.symb=".$dbh->quote($symb);
1.57      matthew  1680:         }
                   1681:     } elsif (defined($symb) && $symb ne '') {
                   1682:         $request .= "FROM $symb_table as d ".
                   1683:             "LEFT JOIN $performance_table AS a ON d.symb_id=a.symb_id ".
1.73      matthew  1684: #            "LEFT JOIN $part_table    AS c ON c.part_id = a.part_id ".
1.57      matthew  1685:             "LEFT JOIN $student_table AS b ON b.student_id = a.student_id ".
                   1686:                 "WHERE symb='".$dbh->quote($symb)."'";
                   1687:     }
                   1688:     my $starttime = Time::HiRes::time;
                   1689:     my $rows_retrieved = 0;
                   1690:     my $sth = $dbh->prepare($request);
                   1691:     $sth->execute();
                   1692:     if ($sth->err()) {
                   1693:         &Apache::lonnet::logthis("Unable to execute MySQL request:");
                   1694:         &Apache::lonnet::logthis("\n".$request."\n");
                   1695:         &Apache::lonnet::logthis("error is:".$sth->errstr());
                   1696:         return undef;
                   1697:     }
                   1698:     foreach my $row (@{$sth->fetchall_arrayref}) {
                   1699:         $rows_retrieved++;
1.63      matthew  1700:         my ($symb,$part,$solved,$tries,$awarded,$award,$awarddetail,$time) = 
1.57      matthew  1701:             (@$row);
                   1702:         my $base = 'resource.'.$part;
                   1703:         $studentdata->{$symb}->{$base.'.solved'}  = $solved;
                   1704:         $studentdata->{$symb}->{$base.'.tries'}   = $tries;
                   1705:         $studentdata->{$symb}->{$base.'.awarded'} = $awarded;
                   1706:         $studentdata->{$symb}->{$base.'.award'}   = $award;
                   1707:         $studentdata->{$symb}->{$base.'.awarddetail'} = $awarddetail;
                   1708:         $studentdata->{$symb}->{'timestamp'} = $time if (defined($time) && $time ne '');
1.67      matthew  1709:     }
1.97      matthew  1710:     ## Get misc parameters
                   1711:     $request = 'SELECT c.symb,a.parameter,a.value '.
                   1712:         "FROM $student_table AS b ".
                   1713:         "LEFT JOIN $parameters_table AS a ON b.student_id=a.student_id ".
                   1714:         "LEFT JOIN $symb_table AS c ON c.symb_id = a.symb_id ".
                   1715:         "WHERE student='$student'";
                   1716:     if (defined($symb) && $symb ne '') {
                   1717:         $request .= " AND c.symb=".$dbh->quote($symb);
                   1718:     }
                   1719:     $sth = $dbh->prepare($request);
                   1720:     $sth->execute();
                   1721:     if ($sth->err()) {
                   1722:         &Apache::lonnet::logthis("Unable to execute MySQL request:");
                   1723:         &Apache::lonnet::logthis("\n".$request."\n");
                   1724:         &Apache::lonnet::logthis("error is:".$sth->errstr());
                   1725:         if (defined($symb) && $symb ne '') {
                   1726:             $studentdata = $studentdata->{$symb};
                   1727:         }
                   1728:         return $studentdata;
                   1729:     }
                   1730:     #
                   1731:     foreach my $row (@{$sth->fetchall_arrayref}) {
                   1732:         $rows_retrieved++;
                   1733:         my ($symb,$parameter,$value) = (@$row);
                   1734:         $studentdata->{$symb}->{$parameter}  = $value;
                   1735:     }
                   1736:     #
1.67      matthew  1737:     if (defined($symb) && $symb ne '') {
                   1738:         $studentdata = $studentdata->{$symb};
1.57      matthew  1739:     }
                   1740:     return $studentdata;
                   1741: }
                   1742: 
                   1743: ################################################
                   1744: ################################################
                   1745: 
                   1746: =pod
                   1747: 
                   1748: =item &get_current_state()
                   1749: 
                   1750: Input: $sname,$sdom,$symb,$courseid
                   1751: 
                   1752: Output: Described below
1.46      matthew  1753: 
1.47      matthew  1754: Retrieve the current status of a students performance.  $sname and
1.46      matthew  1755: $sdom are the only required parameters.  If $symb is undef the results
1.47      matthew  1756: of an &Apache::lonnet::currentdump() will be returned.  
1.46      matthew  1757: If $courseid is undef it will be retrieved from the environment.
                   1758: 
                   1759: The return structure is based on &Apache::lonnet::currentdump.  If
                   1760: $symb is unspecified, all the students data is returned in a hash of
                   1761: the form:
                   1762: ( 
                   1763:   symb1 => { param1 => value1, param2 => value2 ... },
                   1764:   symb2 => { param1 => value1, param2 => value2 ... },
                   1765: )
                   1766: 
                   1767: If $symb is specified, a hash of 
                   1768: (
                   1769:   param1 => value1, 
                   1770:   param2 => value2,
                   1771: )
                   1772: is returned.
                   1773: 
1.57      matthew  1774: If no data is found for $symb, or if the student has no performance data,
1.46      matthew  1775: an empty list is returned.
                   1776: 
                   1777: =cut
                   1778: 
                   1779: ################################################
                   1780: ################################################
                   1781: sub get_current_state {
1.47      matthew  1782:     my ($sname,$sdom,$symb,$courseid,$forcedownload)=@_;
                   1783:     #
1.46      matthew  1784:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
1.47      matthew  1785:     #
1.61      matthew  1786:     return () if (! defined($sname) || ! defined($sdom));
                   1787:     #
1.57      matthew  1788:     my ($status,$data) = &ensure_current_data($sname,$sdom,$courseid);
1.77      matthew  1789: #    &Apache::lonnet::logthis
                   1790: #        ('sname = '.$sname.
                   1791: #         ' domain = '.$sdom.
                   1792: #         ' status = '.$status.
                   1793: #         ' data is '.(defined($data)?'defined':'undefined'));
1.73      matthew  1794: #    while (my ($symb,$hash) = each(%$data)) {
                   1795: #        &Apache::lonnet::logthis($symb."\n----------------------------------");
                   1796: #        while (my ($key,$value) = each (%$hash)) {
                   1797: #            &Apache::lonnet::logthis("   ".$key." = ".$value);
                   1798: #        }
                   1799: #    }
1.47      matthew  1800:     #
1.79      matthew  1801:     if (defined($data) && defined($symb) && ref($data->{$symb})) {
                   1802:         return %{$data->{$symb}};
                   1803:     } elsif (defined($data) && ! defined($symb) && ref($data)) {
                   1804:         return %$data;
                   1805:     } 
                   1806:     if ($status eq 'no data') {
1.57      matthew  1807:         return ();
                   1808:     } else {
                   1809:         if ($status ne 'okay' && $status ne '') {
                   1810:             &Apache::lonnet::logthis('status = '.$status);
1.47      matthew  1811:             return ();
                   1812:         }
1.57      matthew  1813:         my $returnhash = &get_student_data_from_performance_cache($sname,$sdom,
                   1814:                                                       $symb,$courseid);
                   1815:         return %$returnhash if (defined($returnhash));
1.46      matthew  1816:     }
1.57      matthew  1817:     return ();
1.61      matthew  1818: }
                   1819: 
                   1820: ################################################
                   1821: ################################################
                   1822: 
                   1823: =pod
                   1824: 
                   1825: =item &get_problem_statistics()
                   1826: 
                   1827: Gather data on a given problem.  The database is assumed to be 
                   1828: populated and all local caching variables are assumed to be set
                   1829: properly.  This means you need to call &ensure_current_data for
                   1830: the students you are concerned with prior to calling this routine.
                   1831: 
                   1832: Inputs: $students, $symb, $part, $courseid
                   1833: 
1.64      matthew  1834: =over 4
                   1835: 
                   1836: =item $students is an array of hash references.  
                   1837: Each hash must contain at least the 'username' and 'domain' of a student.
                   1838: 
                   1839: =item $symb is the symb for the problem.
                   1840: 
                   1841: =item $part is the part id you need statistics for
                   1842: 
                   1843: =item $courseid is the course id, of course!
                   1844: 
                   1845: =back
                   1846: 
1.66      matthew  1847: Outputs: See the code for up to date information.  A hash reference is
                   1848: returned.  The hash has the following keys defined:
1.64      matthew  1849: 
                   1850: =over 4
                   1851: 
1.66      matthew  1852: =item num_students The number of students attempting the problem
                   1853:       
                   1854: =item tries The total number of tries for the students
                   1855:       
                   1856: =item max_tries The maximum number of tries taken
                   1857:       
                   1858: =item mean_tries The average number of tries
                   1859:       
                   1860: =item num_solved The number of students able to solve the problem
                   1861:       
                   1862: =item num_override The number of students whose answer is 'correct_by_override'
                   1863:       
                   1864: =item deg_of_diff The degree of difficulty of the problem
                   1865:       
                   1866: =item std_tries The standard deviation of the number of tries
                   1867:       
                   1868: =item skew_tries The skew of the number of tries
1.64      matthew  1869: 
1.66      matthew  1870: =item per_wrong The number of students attempting the problem who were not
                   1871: able to answer it correctly.
1.64      matthew  1872: 
                   1873: =back
                   1874: 
1.61      matthew  1875: =cut
                   1876: 
                   1877: ################################################
                   1878: ################################################
                   1879: sub get_problem_statistics {
                   1880:     my ($students,$symb,$part,$courseid) = @_;
                   1881:     return if (! defined($symb) || ! defined($part));
                   1882:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
                   1883:     #
1.100     matthew  1884:     &setup_table_names($courseid);
1.61      matthew  1885:     my $symb_id = &get_symb_id($symb);
                   1886:     my $part_id = &get_part_id($part);
                   1887:     my $stats_table = $courseid.'_problem_stats';
                   1888:     #
                   1889:     my $dbh = &Apache::lonmysql::get_dbh();
                   1890:     return undef if (! defined($dbh));
                   1891:     #
                   1892:     # A) Number of Students attempting problem
                   1893:     # B) Total number of tries of students attempting problem
                   1894:     # C) Mod (largest number of tries for solving the problem)
                   1895:     # D) Mean (average number of tries for solving the problem)
                   1896:     # E) Number of students to solve the problem
                   1897:     # F) Number of students to solve the problem by override
                   1898:     # G) Number of students unable to solve the problem
                   1899:     # H) Degree of difficulty : 1-(E+F)/B
                   1900:     # I) Standard deviation of number of tries
                   1901:     # J) Skew of tries: sqrt(sum(Xi-D)^3)/A
                   1902:     #
                   1903:     $dbh->do('DROP TABLE '.$stats_table);  # May return an error
                   1904:     my $request = 
                   1905:         'CREATE TEMPORARY TABLE '.$stats_table.
                   1906:             ' SELECT student_id,solved,award,tries FROM '.$performance_table.
                   1907:                 ' WHERE symb_id='.$symb_id.' AND part_id='.$part_id;
1.64      matthew  1908:     if (defined($students)) {
                   1909:         $request .= ' AND ('.
                   1910:             join(' OR ', map {'student_id='.
                   1911:                                   &get_student_id($_->{'username'},
                   1912:                                                   $_->{'domain'})
                   1913:                                   } @$students
                   1914:                  ).')';
                   1915:     }
1.61      matthew  1916: #    &Apache::lonnet::logthis($request);
                   1917:     $dbh->do($request);
                   1918:     my ($num,$tries,$mod,$mean,$STD) = &execute_SQL_request
                   1919:         ($dbh,
                   1920:          'SELECT COUNT(*),SUM(tries),MAX(tries),AVG(tries),STD(tries) FROM '.
                   1921:          $stats_table);
                   1922:     my ($Solved) = &execute_SQL_request($dbh,'SELECT COUNT(tries) FROM '.
                   1923:                                         $stats_table.
1.92      matthew  1924:          " WHERE solved='correct_by_student' OR solved='correct_by_scantron'");
1.61      matthew  1925:     my ($solved) = &execute_SQL_request($dbh,'SELECT COUNT(tries) FROM '.
                   1926:                                         $stats_table.
                   1927:                                         " WHERE solved='correct_by_override'");
                   1928:     $num    = 0 if (! defined($num));
                   1929:     $tries  = 0 if (! defined($tries));
                   1930:     $mod    = 0 if (! defined($mod));
                   1931:     $STD    = 0 if (! defined($STD));
                   1932:     $Solved = 0 if (! defined($Solved));
                   1933:     $solved = 0 if (! defined($solved));
                   1934:     #
                   1935:     my $DegOfDiff = 'nan';
1.66      matthew  1936:     $DegOfDiff = 1-($Solved)/$tries if ($tries>0);
1.61      matthew  1937: 
                   1938:     my $SKEW = 'nan';
1.66      matthew  1939:     my $wrongpercent = 0;
1.61      matthew  1940:     if ($num > 0) {
                   1941:         ($SKEW) = &execute_SQL_request($dbh,'SELECT SQRT(SUM('.
                   1942:                                      'POWER(tries - '.$STD.',3)'.
                   1943:                                      '))/'.$num.' FROM '.$stats_table);
1.66      matthew  1944:         $wrongpercent=int(10*100*($num-$Solved+$solved)/$num)/10;
1.61      matthew  1945:     }
                   1946:     #
                   1947:     $dbh->do('DROP TABLE '.$stats_table);  # May return an error
1.81      matthew  1948:     #
                   1949:     # Store in metadata
                   1950:     #
1.80      www      1951:     if ($num) {
                   1952: 	my %storestats=();
                   1953: 
1.86      www      1954:         my $urlres=(&Apache::lonnet::decode_symb($symb))[2];
1.80      www      1955: 
                   1956: 	$storestats{$courseid.'___'.$urlres.'___timestamp'}=time;       
                   1957: 	$storestats{$courseid.'___'.$urlres.'___stdno'}=$num;
                   1958: 	$storestats{$courseid.'___'.$urlres.'___avetries'}=$mean;	   
                   1959: 	$storestats{$courseid.'___'.$urlres.'___difficulty'}=$DegOfDiff;
                   1960: 
                   1961: 	$urlres=~/^(\w+)\/(\w+)/; 
                   1962: 	&Apache::lonnet::put('nohist_resevaldata',\%storestats,$1,$2); 
                   1963:     }
1.81      matthew  1964:     #
                   1965:     # Return result
                   1966:     #
1.66      matthew  1967:     return { num_students => $num,
                   1968:              tries        => $tries,
                   1969:              max_tries    => $mod,
                   1970:              mean_tries   => $mean,
                   1971:              std_tries    => $STD,
                   1972:              skew_tries   => $SKEW,
                   1973:              num_solved   => $Solved,
                   1974:              num_override => $solved,
                   1975:              per_wrong    => $wrongpercent,
1.81      matthew  1976:              deg_of_diff  => $DegOfDiff };
1.61      matthew  1977: }
                   1978: 
                   1979: sub execute_SQL_request {
                   1980:     my ($dbh,$request)=@_;
                   1981: #    &Apache::lonnet::logthis($request);
                   1982:     my $sth = $dbh->prepare($request);
                   1983:     $sth->execute();
                   1984:     my $row = $sth->fetchrow_arrayref();
                   1985:     if (ref($row) eq 'ARRAY' && scalar(@$row)>0) {
                   1986:         return @$row;
                   1987:     }
                   1988:     return ();
                   1989: }
                   1990: 
1.105     matthew  1991: sub get_student_data {
                   1992:     my ($students,$courseid) = @_;
                   1993:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
                   1994:     &setup_table_names($courseid);
                   1995:     my $dbh = &Apache::lonmysql::get_dbh();
                   1996:     return undef if (! defined($dbh));
                   1997:     my $request = 'SELECT '.
                   1998:         'student_id, student '.
                   1999:         'FROM '.$student_table;
                   2000:     if (defined($students)) {
                   2001:         $request .= ' WHERE ('.
                   2002:             join(' OR ', map {'student_id='.
                   2003:                                   &get_student_id($_->{'username'},
                   2004:                                                   $_->{'domain'})
                   2005:                               } @$students
                   2006:                  ).')';
                   2007:     }
                   2008:     $request.= ' ORDER BY student_id';
                   2009:     my $sth = $dbh->prepare($request);
                   2010:     $sth->execute();
                   2011:     if ($dbh->err) {
                   2012:         &Apache::lonnet::logthis('error = '.$dbh->errstr());
                   2013:         return undef;
                   2014:     }
                   2015:     my $dataset = $sth->fetchall_arrayref();
                   2016:     if (ref($dataset) eq 'ARRAY' && scalar(@$dataset)>0) {
                   2017:         return $dataset;
                   2018:     }
                   2019: }
                   2020: 
1.100     matthew  2021: sub get_optionresponse_data {
                   2022:     my ($students,$symb,$response,$courseid) = @_;
1.103     matthew  2023:     return undef if (! defined($symb) || 
1.100     matthew  2024:                ! defined($response));
                   2025:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
                   2026:     #
                   2027:     &setup_table_names($courseid);
                   2028:     my $symb_id = &get_symb_id($symb);
                   2029:     my $response_id = &get_part_id($response);
                   2030:     #
                   2031:     my $dbh = &Apache::lonmysql::get_dbh();
                   2032:     return undef if (! defined($dbh));
                   2033:     my $request = 'SELECT '.
1.105     matthew  2034:         'a.student_id, a.awarddetail, a.response_specific_value, '.
                   2035:         'a.submission, b.timestamp, c.tries '.
1.100     matthew  2036:         'FROM '.$fulldump_response_table.' AS a '.
                   2037:         'LEFT JOIN '.$fulldump_timestamp_table.' AS b '.
                   2038:         'ON a.symb_id=b.symb_id AND a.student_id=b.student_id AND '.
                   2039:         'a.transaction = b.transaction '.
                   2040:         'LEFT JOIN '.$fulldump_part_table.' AS c '.
                   2041:         'ON a.symb_id=c.symb_id AND a.student_id=c.student_id AND '.        
                   2042:         'a.part_id=c.part_id AND a.transaction = c.transaction '.
                   2043:         'WHERE '.
                   2044:         'a.symb_id='.$symb_id.' AND a.response_id='.$response_id;
                   2045:     if (defined($students)) {
                   2046:         $request .= ' AND ('.
1.103     matthew  2047:             join(' OR ', map {'a.student_id='.
1.100     matthew  2048:                                   &get_student_id($_->{'username'},
                   2049:                                                   $_->{'domain'})
                   2050:                               } @$students
                   2051:                  ).')';
                   2052:     }
                   2053:     $request .= ' ORDER BY b.timestamp';
1.103     matthew  2054: #    &Apache::lonnet::logthis("request =\n".$request);
1.100     matthew  2055:     my $sth = $dbh->prepare($request);
                   2056:     $sth->execute();
1.105     matthew  2057:     if ($dbh->err) {
                   2058:         &Apache::lonnet::logthis('error = '.$dbh->errstr());
                   2059:         return undef;
                   2060:     }
1.100     matthew  2061:     my $dataset = $sth->fetchall_arrayref();
                   2062:     if (ref($dataset) eq 'ARRAY' && scalar(@$dataset)>0) {
1.103     matthew  2063:         return $dataset;
1.100     matthew  2064:     }
1.106   ! matthew  2065: }
        !          2066: 
        !          2067: sub get_response_time_data {
        !          2068:     my ($students,$symb,$response,$courseid) = @_;
        !          2069:     return undef if (! defined($symb) || 
        !          2070:                      ! defined($response));
        !          2071:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
        !          2072:     #
        !          2073:     &setup_table_names($courseid);
        !          2074:     my $symb_id = &get_symb_id($symb);
        !          2075:     my $response_id = &get_part_id($response);
        !          2076:     #
        !          2077:     my $dbh = &Apache::lonmysql::get_dbh();
        !          2078:     return undef if (! defined($dbh));
        !          2079:     my $request = 'SELECT '.
        !          2080:         'a.student_id, a.awarddetail, b.timestamp '.
        !          2081:         'FROM '.$fulldump_response_table.' AS a '.
        !          2082:         'NATURAL LEFT JOIN '.$fulldump_timestamp_table.' AS b '.
        !          2083: #        'ON a.symb_id=b.symb_id AND a.student_id=b.student_id AND '.
        !          2084: #        'a.transaction = b.transaction '.
        !          2085:         'WHERE '.
        !          2086:         'a.symb_id='.$symb_id.' AND a.response_id='.$response_id;
        !          2087:     if (defined($students)) {
        !          2088:         $request .= ' AND ('.
        !          2089:             join(' OR ', map {'a.student_id='.
        !          2090:                                   &get_student_id($_->{'username'},
        !          2091:                                                   $_->{'domain'})
        !          2092:                               } @$students
        !          2093:                  ).')';
        !          2094:     }
        !          2095:     $request .= ' ORDER BY b.timestamp';
        !          2096: #    &Apache::lonnet::logthis("request =\n".$request);
        !          2097:     my $sth = $dbh->prepare($request);
        !          2098:     $sth->execute();
        !          2099:     if ($dbh->err) {
        !          2100:         &Apache::lonnet::logthis('error = '.$dbh->errstr());
        !          2101:         return undef;
        !          2102:     }
        !          2103:     my $dataset = $sth->fetchall_arrayref();
        !          2104:     if (ref($dataset) eq 'ARRAY' && scalar(@$dataset)>0) {
        !          2105:         return $dataset;
        !          2106:     }
        !          2107: 
1.100     matthew  2108: }
1.61      matthew  2109: 
                   2110: ################################################
                   2111: ################################################
                   2112: 
                   2113: =pod
                   2114: 
                   2115: =item &setup_table_names()
                   2116: 
                   2117: input: course id
                   2118: 
                   2119: output: none
                   2120: 
                   2121: Cleans up the package variables for local caching.
                   2122: 
                   2123: =cut
                   2124: 
                   2125: ################################################
                   2126: ################################################
                   2127: sub setup_table_names {
                   2128:     my ($courseid) = @_;
                   2129:     if (! defined($courseid)) {
                   2130:         $courseid = $ENV{'request.course.id'};
                   2131:     }
                   2132:     #
                   2133:     if (! defined($current_course) || $current_course ne $courseid) {
                   2134:         # Clear out variables
                   2135:         $have_read_part_table = 0;
                   2136:         undef(%ids_by_part);
                   2137:         undef(%parts_by_id);
                   2138:         $have_read_symb_table = 0;
                   2139:         undef(%ids_by_symb);
                   2140:         undef(%symbs_by_id);
                   2141:         $have_read_student_table = 0;
                   2142:         undef(%ids_by_student);
                   2143:         undef(%students_by_id);
                   2144:         #
                   2145:         $current_course = $courseid;
                   2146:     }
                   2147:     #
                   2148:     # Set up database names
                   2149:     my $base_id = $courseid;
                   2150:     $symb_table        = $base_id.'_'.'symb';
                   2151:     $part_table        = $base_id.'_'.'part';
                   2152:     $student_table     = $base_id.'_'.'student';
1.87      matthew  2153:     $studentdata_table = $base_id.'_'.'studentdata';
1.61      matthew  2154:     $performance_table = $base_id.'_'.'performance';
                   2155:     $parameters_table  = $base_id.'_'.'parameters';
1.89      matthew  2156:     $fulldump_part_table      = $base_id.'_'.'partdata';
                   2157:     $fulldump_response_table  = $base_id.'_'.'responsedata';
                   2158:     $fulldump_timestamp_table = $base_id.'_'.'timestampdata';
                   2159:     #
                   2160:     @Tables = (
                   2161:                $symb_table,
                   2162:                $part_table,
                   2163:                $student_table,
                   2164:                $studentdata_table,
                   2165:                $performance_table,
                   2166:                $parameters_table,
                   2167:                $fulldump_part_table,
                   2168:                $fulldump_response_table,
                   2169:                $fulldump_timestamp_table,
                   2170:                );
1.61      matthew  2171:     return;
1.3       stredwic 2172: }
1.1       stredwic 2173: 
1.35      matthew  2174: ################################################
                   2175: ################################################
                   2176: 
                   2177: =pod
                   2178: 
1.57      matthew  2179: =back
                   2180: 
                   2181: =item End of Local Data Caching Subroutines
                   2182: 
                   2183: =cut
                   2184: 
                   2185: ################################################
                   2186: ################################################
                   2187: 
1.89      matthew  2188: } # End scope of table identifiers
1.57      matthew  2189: 
                   2190: ################################################
                   2191: ################################################
                   2192: 
                   2193: =pod
                   2194: 
                   2195: =head3 Classlist Subroutines
                   2196: 
1.35      matthew  2197: =item &get_classlist();
                   2198: 
                   2199: Retrieve the classist of a given class or of the current class.  Student
                   2200: information is returned from the classlist.db file and, if needed,
                   2201: from the students environment.
                   2202: 
                   2203: Optional arguments are $cid, $cdom, and $cnum (course id, course domain,
                   2204: and course number, respectively).  Any omitted arguments will be taken 
                   2205: from the current environment ($ENV{'request.course.id'},
                   2206: $ENV{'course.'.$cid.'.domain'}, and $ENV{'course.'.$cid.'.num'}).
                   2207: 
                   2208: Returns a reference to a hash which contains:
                   2209:  keys    '$sname:$sdom'
1.54      bowersj2 2210:  values  [$sdom,$sname,$end,$start,$id,$section,$fullname,$status]
                   2211: 
                   2212: The constant values CL_SDOM, CL_SNAME, CL_END, etc. can be used
                   2213: as indices into the returned list to future-proof clients against
                   2214: changes in the list order.
1.35      matthew  2215: 
                   2216: =cut
                   2217: 
                   2218: ################################################
                   2219: ################################################
1.54      bowersj2 2220: 
                   2221: sub CL_SDOM     { return 0; }
                   2222: sub CL_SNAME    { return 1; }
                   2223: sub CL_END      { return 2; }
                   2224: sub CL_START    { return 3; }
                   2225: sub CL_ID       { return 4; }
                   2226: sub CL_SECTION  { return 5; }
                   2227: sub CL_FULLNAME { return 6; }
                   2228: sub CL_STATUS   { return 7; }
1.35      matthew  2229: 
                   2230: sub get_classlist {
                   2231:     my ($cid,$cdom,$cnum) = @_;
                   2232:     $cid = $cid || $ENV{'request.course.id'};
                   2233:     $cdom = $cdom || $ENV{'course.'.$cid.'.domain'};
                   2234:     $cnum = $cnum || $ENV{'course.'.$cid.'.num'};
1.57      matthew  2235:     my $now = time;
1.35      matthew  2236:     #
                   2237:     my %classlist=&Apache::lonnet::dump('classlist',$cdom,$cnum);
                   2238:     while (my ($student,$info) = each(%classlist)) {
1.60      matthew  2239:         if ($student =~ /^(con_lost|error|no_such_host)/i) {
                   2240:             &Apache::lonnet::logthis('get_classlist error for '.$cid.':'.$student);
                   2241:             return undef;
                   2242:         }
1.35      matthew  2243:         my ($sname,$sdom) = split(/:/,$student);
                   2244:         my @Values = split(/:/,$info);
                   2245:         my ($end,$start,$id,$section,$fullname);
                   2246:         if (@Values > 2) {
                   2247:             ($end,$start,$id,$section,$fullname) = @Values;
                   2248:         } else { # We have to get the data ourselves
                   2249:             ($end,$start) = @Values;
1.37      matthew  2250:             $section = &Apache::lonnet::getsection($sdom,$sname,$cid);
1.35      matthew  2251:             my %info=&Apache::lonnet::get('environment',
                   2252:                                           ['firstname','middlename',
                   2253:                                            'lastname','generation','id'],
                   2254:                                           $sdom, $sname);
                   2255:             my ($tmp) = keys(%info);
                   2256:             if ($tmp =~/^(con_lost|error|no_such_host)/i) {
                   2257:                 $fullname = 'not available';
                   2258:                 $id = 'not available';
1.38      matthew  2259:                 &Apache::lonnet::logthis('unable to retrieve environment '.
                   2260:                                          'for '.$sname.':'.$sdom);
1.35      matthew  2261:             } else {
                   2262:                 $fullname = &ProcessFullName(@info{qw/lastname generation 
                   2263:                                                        firstname middlename/});
                   2264:                 $id = $info{'id'};
                   2265:             }
1.36      matthew  2266:             # Update the classlist with this students information
                   2267:             if ($fullname ne 'not available') {
                   2268:                 my $enrolldata = join(':',$end,$start,$id,$section,$fullname);
                   2269:                 my $reply=&Apache::lonnet::cput('classlist',
                   2270:                                                 {$student => $enrolldata},
                   2271:                                                 $cdom,$cnum);
                   2272:                 if ($reply !~ /^(ok|delayed)/) {
                   2273:                     &Apache::lonnet::logthis('Unable to update classlist for '.
                   2274:                                              'student '.$sname.':'.$sdom.
                   2275:                                              ' error:'.$reply);
                   2276:                 }
                   2277:             }
1.35      matthew  2278:         }
                   2279:         my $status='Expired';
                   2280:         if(((!$end) || $now < $end) && ((!$start) || ($now > $start))) {
                   2281:             $status='Active';
                   2282:         }
                   2283:         $classlist{$student} = 
                   2284:             [$sdom,$sname,$end,$start,$id,$section,$fullname,$status];
                   2285:     }
                   2286:     if (wantarray()) {
                   2287:         return (\%classlist,['domain','username','end','start','id',
                   2288:                              'section','fullname','status']);
                   2289:     } else {
                   2290:         return \%classlist;
                   2291:     }
                   2292: }
                   2293: 
1.1       stredwic 2294: # ----- END HELPER FUNCTIONS --------------------------------------------
                   2295: 
                   2296: 1;
                   2297: __END__
1.36      matthew  2298: 
1.35      matthew  2299: 

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