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

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

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