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

1.1       stredwic    1: # The LearningOnline Network with CAPA
                      2: #
1.125   ! matthew     3: # $Id: loncoursedata.pm,v 1.124 2004/03/08 16:14:37 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.121     matthew   185:         next if (! $curRes->is_problem() && $curRes->src() !~ /\.survey$/);
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: 
1.113     matthew   404: The student_table has 7 columns.  The first is a 'student_id' assigned by 
                    405: MySQL.  The second is 'student' which is username:domain.  The third through
                    406: fifth are 'section', 'status' (enrollment status), and 'classification' 
                    407: (to be used in the future).  The sixth and seventh ('updatetime' and 
                    408: 'fullupdatetime') contain the time of last update and full update of student
                    409: data.  This table has its PRIMARY KEY on the 'student_id' column and is indexed
                    410: on 'student', 'section', and 'status'.
1.89      matthew   411: 
                    412: =back 
                    413: 
                    414: =item Tables used to store current status data
                    415: 
                    416: The following tables store data only about the students current status on 
                    417: a problem, meaning only the data related to the last attempt on a problem.
                    418: 
                    419: =over 4
1.57      matthew   420: 
                    421: =item $performance_table
                    422: 
                    423: The performance_table has 9 columns.  The first three are 'symb_id', 
                    424: 'student_id', and 'part_id'.  These comprise the PRIMARY KEY for this table
                    425: and are directly related to the $symb_table, $student_table, and $part_table
                    426: described above.  MySQL does better indexing on numeric items than text,
                    427: so we use these three "index tables".  The remaining columns are
                    428: 'solved', 'tries', 'awarded', 'award', 'awarddetail', and 'timestamp'.
                    429: These are either the MySQL type TINYTEXT or various integers ('tries' and 
                    430: 'timestamp').  This table has KEYs of 'student_id' and 'symb_id'.
                    431: For use of this table, see the functions described below.
                    432: 
                    433: =item $parameters_table
                    434: 
                    435: The parameters_table holds the data that does not fit neatly into the
                    436: performance_table.  The parameters table has four columns: 'symb_id',
                    437: 'student_id', 'parameter', and 'value'.  'symb_id', 'student_id', and
                    438: 'parameter' comprise the PRIMARY KEY for this table.  'parameter' is 
                    439: limited to 255 characters.  'value' is limited to 64k characters.
                    440: 
                    441: =back
                    442: 
1.89      matthew   443: =item Tables used for storing historic data
                    444: 
                    445: The following tables are used to store almost all of the transactions a student
                    446: has made on a homework problem.  See loncapa/docs/homework/datastorage for 
                    447: specific information about each of the parameters stored.  
                    448: 
                    449: =over 4
                    450: 
                    451: =item $fulldump_response_table
                    452: 
                    453: The response table holds data (documented in loncapa/docs/homework/datastorage)
                    454: associated with a particular response id which is stored when a student 
                    455: attempts a problem.  The following are the columns of the table, in order:
                    456: 'symb_id','part_id','response_id','student_id','transaction','tries',
1.93      matthew   457: 'awarddetail', 'response_specific' (data particular to the response
1.89      matthew   458: type), 'response_specific_value', and 'submission (the text of the students
                    459: submission).  The primary key is based on the first five columns listed above.
                    460: 
                    461: =item $fulldump_part_table
                    462: 
                    463: The part table holds data (documented in loncapa/docs/homework/datastorage)
                    464: associated with a particular part id which is stored when a student attempts
                    465: a problem.  The following are the columns of the table, in order:
                    466: 'symb_id','part_id','student_id','transaction','tries','award','awarded',
                    467: and 'previous'.  The primary key is based on the first five columns listed 
                    468: above.
                    469: 
                    470: =item $fulldump_timestamp_table
                    471: 
                    472: The timestamp table holds the timestamps of the transactions which are
                    473: stored in $fulldump_response_table and $fulldump_part_table.  This data is
                    474: about both the response and part data.  Columns: 'symb_id','student_id',
                    475: 'transaction', and 'timestamp'.  
                    476: The primary key is based on the first 3 columns.
                    477: 
                    478: =back
                    479: 
                    480: =back
                    481: 
1.57      matthew   482: =head3 Important Subroutines
                    483: 
                    484: Here is a brief overview of the subroutines which are likely to be of 
                    485: interest:
                    486: 
                    487: =over 4
                    488: 
                    489: =item &get_current_state(): programmers interface.
                    490: 
                    491: =item &init_dbs(): table creation
                    492: 
                    493: =item &update_student_data(): data storage calls
                    494: 
                    495: =item &get_student_data_from_performance_cache(): data retrieval
                    496: 
                    497: =back
                    498: 
                    499: =head3 Main Documentation
                    500: 
                    501: =over 4
                    502: 
                    503: =cut
                    504: 
                    505: ################################################
                    506: ################################################
                    507: 
                    508: ################################################
                    509: ################################################
1.89      matthew   510: { # Begin scope of table identifiers
1.57      matthew   511: 
                    512: my $current_course ='';
                    513: my $symb_table;
                    514: my $part_table;
                    515: my $student_table;
                    516: my $performance_table;
                    517: my $parameters_table;
1.89      matthew   518: my $fulldump_response_table;
                    519: my $fulldump_part_table;
                    520: my $fulldump_timestamp_table;
1.57      matthew   521: 
1.89      matthew   522: my @Tables;
1.57      matthew   523: ################################################
                    524: ################################################
                    525: 
                    526: =pod
                    527: 
                    528: =item &init_dbs()
                    529: 
                    530: Input: course id
                    531: 
                    532: Output: 0 on success, positive integer on error
                    533: 
                    534: This routine issues the calls to lonmysql to create the tables used to
                    535: store student data.
                    536: 
                    537: =cut
                    538: 
                    539: ################################################
                    540: ################################################
                    541: sub init_dbs {
                    542:     my $courseid = shift;
                    543:     &setup_table_names($courseid);
                    544:     #
1.73      matthew   545:     # Drop any of the existing tables
1.89      matthew   546:     foreach my $table (@Tables) {
1.73      matthew   547:         &Apache::lonmysql::drop_table($table);
                    548:     }
                    549:     #
1.57      matthew   550:     # Note - changes to this table must be reflected in the code that 
                    551:     # stores the data (calls &Apache::lonmysql::store_row with this table
                    552:     # id
                    553:     my $symb_table_def = {
                    554:         id => $symb_table,
                    555:         permanent => 'no',
                    556:         columns => [{ name => 'symb_id',
                    557:                       type => 'MEDIUMINT UNSIGNED',
                    558:                       restrictions => 'NOT NULL',
                    559:                       auto_inc     => 'yes', },
                    560:                     { name => 'symb',
                    561:                       type => 'MEDIUMTEXT',
                    562:                       restrictions => 'NOT NULL'},
                    563:                     ],
                    564:         'PRIMARY KEY' => ['symb_id'],
                    565:     };
                    566:     #
                    567:     my $part_table_def = {
                    568:         id => $part_table,
                    569:         permanent => 'no',
                    570:         columns => [{ name => 'part_id',
                    571:                       type => 'MEDIUMINT UNSIGNED',
                    572:                       restrictions => 'NOT NULL',
                    573:                       auto_inc     => 'yes', },
                    574:                     { name => 'part',
                    575:                       type => 'VARCHAR(100)',
                    576:                       restrictions => 'NOT NULL'},
                    577:                     ],
                    578:         'PRIMARY KEY' => ['part (100)'],
                    579:         'KEY' => [{ columns => ['part_id']},],
                    580:     };
                    581:     #
                    582:     my $student_table_def = {
                    583:         id => $student_table,
                    584:         permanent => 'no',
                    585:         columns => [{ name => 'student_id',
                    586:                       type => 'MEDIUMINT UNSIGNED',
                    587:                       restrictions => 'NOT NULL',
                    588:                       auto_inc     => 'yes', },
                    589:                     { name => 'student',
                    590:                       type => 'VARCHAR(100)',
1.113     matthew   591:                       restrictions => 'NOT NULL UNIQUE'},
                    592:                     { name => 'section',
                    593:                       type => 'VARCHAR(100)',
                    594:                       restrictions => 'NOT NULL'},
                    595:                     { name => 'status',
                    596:                       type => 'VARCHAR(15)',
1.57      matthew   597:                       restrictions => 'NOT NULL'},
1.85      matthew   598:                     { name => 'classification',
                    599:                       type => 'varchar(100)', },
1.57      matthew   600:                     { name => 'updatetime',
1.89      matthew   601:                       type => 'INT UNSIGNED'},
                    602:                     { name => 'fullupdatetime',
                    603:                       type => 'INT UNSIGNED'},
1.57      matthew   604:                     ],
1.87      matthew   605:         'PRIMARY KEY' => ['student_id'],
1.113     matthew   606:         'KEY' => [{ columns => ['student (100)',
                    607:                                 'section (100)',
                    608:                                 'status (15)',]},],
1.57      matthew   609:     };
                    610:     #
                    611:     my $performance_table_def = {
                    612:         id => $performance_table,
                    613:         permanent => 'no',
                    614:         columns => [{ name => 'symb_id',
                    615:                       type => 'MEDIUMINT UNSIGNED',
                    616:                       restrictions => 'NOT NULL'  },
                    617:                     { name => 'student_id',
                    618:                       type => 'MEDIUMINT UNSIGNED',
                    619:                       restrictions => 'NOT NULL'  },
                    620:                     { name => 'part_id',
                    621:                       type => 'MEDIUMINT UNSIGNED',
                    622:                       restrictions => 'NOT NULL' },
1.73      matthew   623:                     { name => 'part',
                    624:                       type => 'VARCHAR(100)',
                    625:                       restrictions => 'NOT NULL'},                    
1.57      matthew   626:                     { name => 'solved',
                    627:                       type => 'TINYTEXT' },
                    628:                     { name => 'tries',
                    629:                       type => 'SMALLINT UNSIGNED' },
                    630:                     { name => 'awarded',
                    631:                       type => 'TINYTEXT' },
                    632:                     { name => 'award',
                    633:                       type => 'TINYTEXT' },
                    634:                     { name => 'awarddetail',
                    635:                       type => 'TINYTEXT' },
                    636:                     { name => 'timestamp',
                    637:                       type => 'INT UNSIGNED'},
                    638:                     ],
                    639:         'PRIMARY KEY' => ['symb_id','student_id','part_id'],
                    640:         'KEY' => [{ columns=>['student_id'] },
                    641:                   { columns=>['symb_id'] },],
                    642:     };
                    643:     #
1.89      matthew   644:     my $fulldump_part_table_def = {
                    645:         id => $fulldump_part_table,
                    646:         permanent => 'no',
                    647:         columns => [
                    648:                     { name => 'symb_id',
                    649:                       type => 'MEDIUMINT UNSIGNED',
                    650:                       restrictions => 'NOT NULL'  },
                    651:                     { name => 'part_id',
                    652:                       type => 'MEDIUMINT UNSIGNED',
                    653:                       restrictions => 'NOT NULL' },
                    654:                     { name => 'student_id',
                    655:                       type => 'MEDIUMINT UNSIGNED',
                    656:                       restrictions => 'NOT NULL'  },
                    657:                     { name => 'transaction',
                    658:                       type => 'MEDIUMINT UNSIGNED',
                    659:                       restrictions => 'NOT NULL' },
                    660:                     { name => 'tries',
                    661:                       type => 'SMALLINT UNSIGNED',
                    662:                       restrictions => 'NOT NULL' },
                    663:                     { name => 'award',
                    664:                       type => 'TINYTEXT' },
                    665:                     { name => 'awarded',
                    666:                       type => 'TINYTEXT' },
                    667:                     { name => 'previous',
                    668:                       type => 'SMALLINT UNSIGNED' },
                    669: #                    { name => 'regrader',
                    670: #                      type => 'TINYTEXT' },
                    671: #                    { name => 'afterduedate',
                    672: #                      type => 'TINYTEXT' },
                    673:                     ],
                    674:         'PRIMARY KEY' => ['symb_id','part_id','student_id','transaction'],
                    675:         'KEY' => [
                    676:                   { columns=>['symb_id'] },
                    677:                   { columns=>['part_id'] },
                    678:                   { columns=>['student_id'] },
                    679:                   ],
                    680:     };
                    681:     #
                    682:     my $fulldump_response_table_def = {
                    683:         id => $fulldump_response_table,
                    684:         permanent => 'no',
                    685:         columns => [
                    686:                     { name => 'symb_id',
                    687:                       type => 'MEDIUMINT UNSIGNED',
                    688:                       restrictions => 'NOT NULL'  },
                    689:                     { name => 'part_id',
                    690:                       type => 'MEDIUMINT UNSIGNED',
                    691:                       restrictions => 'NOT NULL' },
                    692:                     { name => 'response_id',
                    693:                       type => 'MEDIUMINT UNSIGNED',
                    694:                       restrictions => 'NOT NULL'  },
                    695:                     { name => 'student_id',
                    696:                       type => 'MEDIUMINT UNSIGNED',
                    697:                       restrictions => 'NOT NULL'  },
                    698:                     { name => 'transaction',
                    699:                       type => 'MEDIUMINT UNSIGNED',
                    700:                       restrictions => 'NOT NULL' },
                    701:                     { name => 'awarddetail',
                    702:                       type => 'TINYTEXT' },
                    703: #                    { name => 'message',
                    704: #                      type => 'CHAR' },
                    705:                     { name => 'response_specific',
                    706:                       type => 'TINYTEXT' },
                    707:                     { name => 'response_specific_value',
                    708:                       type => 'TINYTEXT' },
                    709:                     { name => 'submission',
                    710:                       type => 'TEXT'},
                    711:                     ],
                    712:             'PRIMARY KEY' => ['symb_id','part_id','response_id','student_id',
                    713:                               'transaction'],
                    714:             'KEY' => [
                    715:                       { columns=>['symb_id'] },
                    716:                       { columns=>['part_id','response_id'] },
                    717:                       { columns=>['student_id'] },
                    718:                       ],
                    719:     };
                    720:     my $fulldump_timestamp_table_def = {
                    721:         id => $fulldump_timestamp_table,
                    722:         permanent => 'no',
                    723:         columns => [
                    724:                     { name => 'symb_id',
                    725:                       type => 'MEDIUMINT UNSIGNED',
                    726:                       restrictions => 'NOT NULL'  },
                    727:                     { name => 'student_id',
                    728:                       type => 'MEDIUMINT UNSIGNED',
                    729:                       restrictions => 'NOT NULL'  },
                    730:                     { name => 'transaction',
                    731:                       type => 'MEDIUMINT UNSIGNED',
                    732:                       restrictions => 'NOT NULL' },
                    733:                     { name => 'timestamp',
                    734:                       type => 'INT UNSIGNED'},
                    735:                     ],
                    736:         'PRIMARY KEY' => ['symb_id','student_id','transaction'],
                    737:         'KEY' => [
                    738:                   { columns=>['symb_id'] },
                    739:                   { columns=>['student_id'] },
                    740:                   { columns=>['transaction'] },
                    741:                   ],
                    742:     };
                    743: 
                    744:     #
1.57      matthew   745:     my $parameters_table_def = {
                    746:         id => $parameters_table,
                    747:         permanent => 'no',
                    748:         columns => [{ name => 'symb_id',
                    749:                       type => 'MEDIUMINT UNSIGNED',
                    750:                       restrictions => 'NOT NULL'  },
                    751:                     { name => 'student_id',
                    752:                       type => 'MEDIUMINT UNSIGNED',
                    753:                       restrictions => 'NOT NULL'  },
                    754:                     { name => 'parameter',
                    755:                       type => 'TINYTEXT',
                    756:                       restrictions => 'NOT NULL'  },
                    757:                     { name => 'value',
                    758:                       type => 'MEDIUMTEXT' },
                    759:                     ],
                    760:         'PRIMARY KEY' => ['symb_id','student_id','parameter (255)'],
                    761:     };
                    762:     #
                    763:     # Create the tables
                    764:     my $tableid;
                    765:     $tableid = &Apache::lonmysql::create_table($symb_table_def);
                    766:     if (! defined($tableid)) {
                    767:         &Apache::lonnet::logthis("error creating symb_table: ".
                    768:                                  &Apache::lonmysql::get_error());
                    769:         return 1;
                    770:     }
                    771:     #
                    772:     $tableid = &Apache::lonmysql::create_table($part_table_def);
                    773:     if (! defined($tableid)) {
                    774:         &Apache::lonnet::logthis("error creating part_table: ".
                    775:                                  &Apache::lonmysql::get_error());
                    776:         return 2;
                    777:     }
                    778:     #
                    779:     $tableid = &Apache::lonmysql::create_table($student_table_def);
                    780:     if (! defined($tableid)) {
                    781:         &Apache::lonnet::logthis("error creating student_table: ".
                    782:                                  &Apache::lonmysql::get_error());
                    783:         return 3;
                    784:     }
                    785:     #
                    786:     $tableid = &Apache::lonmysql::create_table($performance_table_def);
                    787:     if (! defined($tableid)) {
                    788:         &Apache::lonnet::logthis("error creating preformance_table: ".
                    789:                                  &Apache::lonmysql::get_error());
                    790:         return 5;
                    791:     }
                    792:     #
                    793:     $tableid = &Apache::lonmysql::create_table($parameters_table_def);
                    794:     if (! defined($tableid)) {
                    795:         &Apache::lonnet::logthis("error creating parameters_table: ".
                    796:                                  &Apache::lonmysql::get_error());
                    797:         return 6;
                    798:     }
1.89      matthew   799:     #
                    800:     $tableid = &Apache::lonmysql::create_table($fulldump_part_table_def);
                    801:     if (! defined($tableid)) {
                    802:         &Apache::lonnet::logthis("error creating fulldump_part_table: ".
                    803:                                  &Apache::lonmysql::get_error());
                    804:         return 7;
                    805:     }
                    806:     #
                    807:     $tableid = &Apache::lonmysql::create_table($fulldump_response_table_def);
                    808:     if (! defined($tableid)) {
                    809:         &Apache::lonnet::logthis("error creating fulldump_response_table: ".
                    810:                                  &Apache::lonmysql::get_error());
                    811:         return 8;
                    812:     }
                    813:     $tableid = &Apache::lonmysql::create_table($fulldump_timestamp_table_def);
                    814:     if (! defined($tableid)) {
                    815:         &Apache::lonnet::logthis("error creating fulldump_timestamp_table: ".
                    816:                                  &Apache::lonmysql::get_error());
                    817:         return 9;
                    818:     }
1.57      matthew   819:     return 0;
1.70      matthew   820: }
                    821: 
                    822: ################################################
                    823: ################################################
                    824: 
                    825: =pod
                    826: 
                    827: =item &delete_caches()
                    828: 
                    829: =cut
                    830: 
                    831: ################################################
                    832: ################################################
                    833: sub delete_caches {
                    834:     my $courseid = shift;
                    835:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
                    836:     #
                    837:     &setup_table_names($courseid);
                    838:     #
                    839:     my $dbh = &Apache::lonmysql::get_dbh();
1.89      matthew   840:     foreach my $table (@Tables) {
1.70      matthew   841:         my $command = 'DROP TABLE '.$table.';';
                    842:         $dbh->do($command);
                    843:         if ($dbh->err) {
                    844:             &Apache::lonnet::logthis($command.' resulted in error: '.$dbh->errstr);
                    845:         }
                    846:     }
                    847:     return;
1.57      matthew   848: }
                    849: 
                    850: ################################################
                    851: ################################################
                    852: 
                    853: =pod
                    854: 
                    855: =item &get_part_id()
                    856: 
                    857: Get the MySQL id of a problem part string.
                    858: 
                    859: Input: $part
                    860: 
                    861: Output: undef on error, integer $part_id on success.
                    862: 
                    863: =item &get_part()
                    864: 
                    865: Get the string describing a part from the MySQL id of the problem part.
                    866: 
                    867: Input: $part_id
                    868: 
                    869: Output: undef on error, $part string on success.
                    870: 
                    871: =cut
                    872: 
                    873: ################################################
                    874: ################################################
                    875: 
1.61      matthew   876: my $have_read_part_table = 0;
1.57      matthew   877: my %ids_by_part;
                    878: my %parts_by_id;
                    879: 
                    880: sub get_part_id {
                    881:     my ($part) = @_;
1.61      matthew   882:     $part = 0 if (! defined($part));
                    883:     if (! $have_read_part_table) {
                    884:         my @Result = &Apache::lonmysql::get_rows($part_table);
                    885:         foreach (@Result) {
                    886:             $ids_by_part{$_->[1]}=$_->[0];
                    887:         }
                    888:         $have_read_part_table = 1;
                    889:     }
1.57      matthew   890:     if (! exists($ids_by_part{$part})) {
                    891:         &Apache::lonmysql::store_row($part_table,[undef,$part]);
                    892:         undef(%ids_by_part);
                    893:         my @Result = &Apache::lonmysql::get_rows($part_table);
                    894:         foreach (@Result) {
                    895:             $ids_by_part{$_->[1]}=$_->[0];
                    896:         }
                    897:     }
                    898:     return $ids_by_part{$part} if (exists($ids_by_part{$part}));
                    899:     return undef; # error
                    900: }
                    901: 
                    902: sub get_part {
                    903:     my ($part_id) = @_;
                    904:     if (! exists($parts_by_id{$part_id})  || 
                    905:         ! defined($parts_by_id{$part_id}) ||
                    906:         $parts_by_id{$part_id} eq '') {
                    907:         my @Result = &Apache::lonmysql::get_rows($part_table);
                    908:         foreach (@Result) {
                    909:             $parts_by_id{$_->[0]}=$_->[1];
                    910:         }
                    911:     }
                    912:     return $parts_by_id{$part_id} if(exists($parts_by_id{$part_id}));
                    913:     return undef; # error
                    914: }
                    915: 
                    916: ################################################
                    917: ################################################
                    918: 
                    919: =pod
                    920: 
                    921: =item &get_symb_id()
                    922: 
                    923: Get the MySQL id of a symb.
                    924: 
                    925: Input: $symb
                    926: 
                    927: Output: undef on error, integer $symb_id on success.
                    928: 
                    929: =item &get_symb()
                    930: 
                    931: Get the symb associated with a MySQL symb_id.
                    932: 
                    933: Input: $symb_id
                    934: 
                    935: Output: undef on error, $symb on success.
                    936: 
                    937: =cut
                    938: 
                    939: ################################################
                    940: ################################################
                    941: 
1.61      matthew   942: my $have_read_symb_table = 0;
1.57      matthew   943: my %ids_by_symb;
                    944: my %symbs_by_id;
                    945: 
                    946: sub get_symb_id {
                    947:     my ($symb) = @_;
1.61      matthew   948:     if (! $have_read_symb_table) {
                    949:         my @Result = &Apache::lonmysql::get_rows($symb_table);
                    950:         foreach (@Result) {
                    951:             $ids_by_symb{$_->[1]}=$_->[0];
                    952:         }
                    953:         $have_read_symb_table = 1;
                    954:     }
1.57      matthew   955:     if (! exists($ids_by_symb{$symb})) {
                    956:         &Apache::lonmysql::store_row($symb_table,[undef,$symb]);
                    957:         undef(%ids_by_symb);
                    958:         my @Result = &Apache::lonmysql::get_rows($symb_table);
                    959:         foreach (@Result) {
                    960:             $ids_by_symb{$_->[1]}=$_->[0];
                    961:         }
                    962:     }
                    963:     return $ids_by_symb{$symb} if(exists( $ids_by_symb{$symb}));
                    964:     return undef; # error
                    965: }
                    966: 
                    967: sub get_symb {
                    968:     my ($symb_id) = @_;
                    969:     if (! exists($symbs_by_id{$symb_id})  || 
                    970:         ! defined($symbs_by_id{$symb_id}) ||
                    971:         $symbs_by_id{$symb_id} eq '') {
                    972:         my @Result = &Apache::lonmysql::get_rows($symb_table);
                    973:         foreach (@Result) {
                    974:             $symbs_by_id{$_->[0]}=$_->[1];
                    975:         }
                    976:     }
                    977:     return $symbs_by_id{$symb_id} if(exists( $symbs_by_id{$symb_id}));
                    978:     return undef; # error
                    979: }
                    980: 
                    981: ################################################
                    982: ################################################
                    983: 
                    984: =pod
                    985: 
                    986: =item &get_student_id()
                    987: 
                    988: Get the MySQL id of a student.
                    989: 
                    990: Input: $sname, $dom
                    991: 
                    992: Output: undef on error, integer $student_id on success.
                    993: 
                    994: =item &get_student()
                    995: 
                    996: Get student username:domain associated with the MySQL student_id.
                    997: 
                    998: Input: $student_id
                    999: 
                   1000: Output: undef on error, string $student (username:domain) on success.
                   1001: 
                   1002: =cut
                   1003: 
                   1004: ################################################
                   1005: ################################################
                   1006: 
1.61      matthew  1007: my $have_read_student_table = 0;
1.57      matthew  1008: my %ids_by_student;
                   1009: my %students_by_id;
                   1010: 
                   1011: sub get_student_id {
                   1012:     my ($sname,$sdom) = @_;
                   1013:     my $student = $sname.':'.$sdom;
1.61      matthew  1014:     if (! $have_read_student_table) {
                   1015:         my @Result = &Apache::lonmysql::get_rows($student_table);
                   1016:         foreach (@Result) {
                   1017:             $ids_by_student{$_->[1]}=$_->[0];
                   1018:         }
                   1019:         $have_read_student_table = 1;
                   1020:     }
1.57      matthew  1021:     if (! exists($ids_by_student{$student})) {
1.113     matthew  1022:         &populate_student_table();
1.57      matthew  1023:         undef(%ids_by_student);
1.113     matthew  1024:         undef(%students_by_id);
1.57      matthew  1025:         my @Result = &Apache::lonmysql::get_rows($student_table);
                   1026:         foreach (@Result) {
                   1027:             $ids_by_student{$_->[1]}=$_->[0];
                   1028:         }
                   1029:     }
                   1030:     return $ids_by_student{$student} if(exists( $ids_by_student{$student}));
                   1031:     return undef; # error
                   1032: }
                   1033: 
                   1034: sub get_student {
                   1035:     my ($student_id) = @_;
                   1036:     if (! exists($students_by_id{$student_id})  || 
                   1037:         ! defined($students_by_id{$student_id}) ||
                   1038:         $students_by_id{$student_id} eq '') {
                   1039:         my @Result = &Apache::lonmysql::get_rows($student_table);
                   1040:         foreach (@Result) {
                   1041:             $students_by_id{$_->[0]}=$_->[1];
                   1042:         }
                   1043:     }
                   1044:     return $students_by_id{$student_id} if(exists($students_by_id{$student_id}));
                   1045:     return undef; # error
                   1046: }
1.99      matthew  1047: 
1.113     matthew  1048: sub populate_student_table {
                   1049:     my ($courseid) = @_;
                   1050:     if (! defined($courseid)) {
                   1051:         $courseid = $ENV{'request.course.id'};
                   1052:     }
                   1053:     #
                   1054:     &setup_table_names($courseid);
                   1055:     my $dbh = &Apache::lonmysql::get_dbh();
                   1056:     my $request = 'INSERT IGNORE INTO '.$student_table.
                   1057:         "(student,section,status) VALUES ";
                   1058:     my $classlist = &get_classlist($courseid);
                   1059:     my $student_count=0;
                   1060:     while (my ($student,$data) = each %$classlist) {
                   1061:         my ($section,$status) = ($data->[&CL_SECTION()],
                   1062:                                  $data->[&CL_STATUS()]);
                   1063:         if ($section eq '' || $section =~ /^\s*$/) {
                   1064:             $section = 'none';
                   1065:         }
                   1066:         $request .= "('".$student."','".$section."','".$status."'),";
                   1067:         $student_count++;
                   1068:     }
                   1069:     return if ($student_count == 0);
                   1070:     chop($request);
                   1071:     $dbh->do($request);
                   1072:     if ($dbh->err()) {
                   1073:         &Apache::lonnet::logthis("error ".$dbh->errstr().
                   1074:                                  " occured executing \n".
                   1075:                                  $request);
                   1076:     }
                   1077:     return;
                   1078: }
                   1079: 
                   1080: 
1.99      matthew  1081: ################################################
                   1082: ################################################
                   1083: 
                   1084: =pod
                   1085: 
                   1086: =item &clear_internal_caches()
                   1087: 
                   1088: Causes the internal caches used in get_student_id, get_student,
                   1089: get_symb_id, get_symb, get_part_id, and get_part to be undef'd.
                   1090: 
                   1091: Needs to be called before the first operation with the MySQL database
                   1092: for a given Apache request.
                   1093: 
                   1094: =cut
                   1095: 
                   1096: ################################################
                   1097: ################################################
                   1098: sub clear_internal_caches {
                   1099:     $have_read_part_table = 0;
                   1100:     undef(%ids_by_part);
                   1101:     undef(%parts_by_id);
                   1102:     $have_read_symb_table = 0;
                   1103:     undef(%ids_by_symb);
                   1104:     undef(%symbs_by_id);
                   1105:     $have_read_student_table = 0;
                   1106:     undef(%ids_by_student);
                   1107:     undef(%students_by_id);
                   1108: }
                   1109: 
1.57      matthew  1110: 
                   1111: ################################################
                   1112: ################################################
                   1113: 
                   1114: =pod
                   1115: 
1.89      matthew  1116: =item &update_full_student_data($sname,$sdom,$courseid)
                   1117: 
                   1118: Does a lonnet::dump on a student to populate the courses tables.
                   1119: 
                   1120: Input: $sname, $sdom, $courseid
                   1121: 
                   1122: Output: $returnstatus
                   1123: 
                   1124: $returnstatus is a string describing any errors that occured.  'okay' is the
                   1125: default.
                   1126: 
                   1127: This subroutine loads a students data using lonnet::dump and inserts
                   1128: it into the MySQL database.  The inserts are done on three tables, 
                   1129: $fulldump_response_table, $fulldump_part_table, and $fulldump_timestamp_table.
                   1130: The INSERT calls are made directly by this subroutine, not through lonmysql 
                   1131: because we do a 'bulk'insert which takes advantage of MySQLs non-SQL 
                   1132: compliant INSERT command to insert multiple rows at a time.  
                   1133: If anything has gone wrong during this process, $returnstatus is updated with 
                   1134: a description of the error.
                   1135: 
                   1136: Once the "fulldump" tables are updated, the tables used for chart and
                   1137: spreadsheet (which hold only the current state of the student on their
                   1138: homework, not historical data) are updated.  If all updates have occured 
1.113     matthew  1139: successfully, $student_table is updated to reflect the time of the update.
1.89      matthew  1140: 
                   1141: Notice we do not insert the data and immediately query it.  This means it
                   1142: is possible for there to be data returned this first time that is not 
                   1143: available the second time.  CYA.
                   1144: 
                   1145: =cut
                   1146: 
                   1147: ################################################
                   1148: ################################################
                   1149: sub update_full_student_data {
                   1150:     my ($sname,$sdom,$courseid) = @_;
                   1151:     #
                   1152:     # Set up database names
                   1153:     &setup_table_names($courseid);
                   1154:     #
                   1155:     my $student_id = &get_student_id($sname,$sdom);
                   1156:     my $student = $sname.':'.$sdom;
                   1157:     #
                   1158:     my $returnstatus = 'okay';
                   1159:     #
                   1160:     # Download students data
                   1161:     my $time_of_retrieval = time;
                   1162:     my @tmp = &Apache::lonnet::dump($courseid,$sdom,$sname);
                   1163:     if (@tmp && $tmp[0] =~ /^error/) {
                   1164:         $returnstatus = 'error retrieving full student data';
                   1165:         return $returnstatus;
                   1166:     } elsif (! @tmp) {
                   1167:         $returnstatus = 'okay: no student data';
                   1168:         return $returnstatus;
                   1169:     }
                   1170:     my %studentdata = @tmp;
                   1171:     #
                   1172:     # Get database handle and clean out the tables 
                   1173:     my $dbh = &Apache::lonmysql::get_dbh();
                   1174:     $dbh->do('DELETE FROM '.$fulldump_response_table.' WHERE student_id='.
                   1175:              $student_id);
                   1176:     $dbh->do('DELETE FROM '.$fulldump_part_table.' WHERE student_id='.
                   1177:              $student_id);
                   1178:     $dbh->do('DELETE FROM '.$fulldump_timestamp_table.' WHERE student_id='.
                   1179:              $student_id);
                   1180:     #
                   1181:     # Parse and store the data into a form we can handle
                   1182:     my $partdata;
                   1183:     my $respdata;
                   1184:     while (my ($key,$value) = each(%studentdata)) {
                   1185:         next if ($key =~ /^(\d+):(resource$|subnum$|keys:)/);
                   1186:         my ($transaction,$symb,$parameter) = split(':',$key);
                   1187:         my $symb_id = &get_symb_id($symb);
                   1188:         if ($parameter eq 'timestamp') {
                   1189:             # We can deal with 'timestamp' right away
                   1190:             my @timestamp_storage = ($symb_id,$student_id,
                   1191:                                      $transaction,$value);
1.98      matthew  1192:             my $store_command = 'INSERT IGNORE INTO '.$fulldump_timestamp_table.
1.89      matthew  1193:                 " VALUES ('".join("','",@timestamp_storage)."');";
                   1194:             $dbh->do($store_command);
                   1195:             if ($dbh->err()) {
                   1196:                 &Apache::lonnet::logthis('unable to execute '.$store_command);
                   1197:                 &Apache::lonnet::logthis($dbh->errstr());
                   1198:             }
                   1199:             next;
                   1200:         } elsif ($parameter eq 'version') {
                   1201:             next;
1.90      matthew  1202:         } elsif ($parameter =~ /^resource\.(.*)\.(tries|
                   1203:                                                   award|
                   1204:                                                   awarded|
                   1205:                                                   previous|
                   1206:                                                   solved|
                   1207:                                                   awarddetail|
                   1208:                                                   submission|
                   1209:                                                   submissiongrading|
                   1210:                                                   molecule)\s*$/x){
1.89      matthew  1211:             # we do not have enough information to store an 
                   1212:             # entire row, so we save it up until later.
                   1213:             my ($part_and_resp_id,$field) = ($1,$2);
                   1214:             my ($part,$part_id,$resp,$resp_id);
                   1215:             if ($part_and_resp_id =~ /\./) {
                   1216:                 ($part,$resp) = split(/\./,$part_and_resp_id);
                   1217:                 $part_id = &get_part_id($part);
                   1218:                 $resp_id = &get_part_id($resp);
                   1219:             } else {
                   1220:                 $part_id = &get_part_id($part_and_resp_id);
                   1221:             }
1.90      matthew  1222:             # Deal with part specific data
1.89      matthew  1223:             if ($field =~ /^(tries|award|awarded|previous)$/) {
                   1224:                 $partdata->{$symb_id}->{$part_id}->{$transaction}->{$field}=$value;
                   1225:             }
1.90      matthew  1226:             # deal with response specific data
1.89      matthew  1227:             if (defined($resp_id) &&
1.100     matthew  1228:                 $field =~ /^(awarddetail|
1.90      matthew  1229:                              submission|
                   1230:                              submissiongrading|
                   1231:                              molecule)$/x) {
1.89      matthew  1232:                 if ($field eq 'submission') {
                   1233:                     # We have to be careful with user supplied input.
                   1234:                     # most of the time we are okay because it is escaped.
                   1235:                     # However, there is one wrinkle: submissions which end in
                   1236:                     # and odd number of '\' cause insert errors to occur.  
                   1237:                     # Best trap this somehow...
1.116     matthew  1238:                     $value = $dbh->quote($value);
1.89      matthew  1239:                 }
1.90      matthew  1240:                 if ($field eq 'submissiongrading' || 
                   1241:                     $field eq 'molecule') {
                   1242:                     $respdata->{$symb_id}->{$part_id}->{$resp_id}->{$transaction}->{'response_specific'}=$field;
                   1243:                     $respdata->{$symb_id}->{$part_id}->{$resp_id}->{$transaction}->{'response_specific_value'}=$value;
                   1244:                 } else {
                   1245:                     $respdata->{$symb_id}->{$part_id}->{$resp_id}->{$transaction}->{$field}=$value;
                   1246:                 }
1.89      matthew  1247:             }
                   1248:         }
                   1249:     }
                   1250:     ##
                   1251:     ## Store the part data
1.98      matthew  1252:     my $store_command = 'INSERT IGNORE INTO '.$fulldump_part_table.
1.89      matthew  1253:         ' VALUES '."\n";
                   1254:     my $store_rows = 0;
                   1255:     while (my ($symb_id,$hash1) = each (%$partdata)) {
                   1256:         while (my ($part_id,$hash2) = each (%$hash1)) {
                   1257:             while (my ($transaction,$data) = each (%$hash2)) {
                   1258:                 $store_command .= "('".join("','",$symb_id,$part_id,
                   1259:                                             $student_id,
                   1260:                                             $transaction,
1.101     matthew  1261:                                             $data->{'tries'},
1.89      matthew  1262:                                             $data->{'award'},
                   1263:                                             $data->{'awarded'},
                   1264:                                             $data->{'previous'})."'),";
                   1265:                 $store_rows++;
                   1266:             }
                   1267:         }
                   1268:     }
                   1269:     if ($store_rows) {
                   1270:         chop($store_command);
                   1271:         $dbh->do($store_command);
                   1272:         if ($dbh->err) {
                   1273:             $returnstatus = 'error storing part data';
                   1274:             &Apache::lonnet::logthis('insert error '.$dbh->errstr());
                   1275:             &Apache::lonnet::logthis("While attempting\n".$store_command);
                   1276:         }
                   1277:     }
                   1278:     ##
                   1279:     ## Store the response data
1.98      matthew  1280:     $store_command = 'INSERT IGNORE INTO '.$fulldump_response_table.
1.89      matthew  1281:         ' VALUES '."\n";
                   1282:     $store_rows = 0;
                   1283:     while (my ($symb_id,$hash1) = each (%$respdata)) {
                   1284:         while (my ($part_id,$hash2) = each (%$hash1)) {
                   1285:             while (my ($resp_id,$hash3) = each (%$hash2)) {
                   1286:                 while (my ($transaction,$data) = each (%$hash3)) {
1.112     matthew  1287:                     my $submission = $data->{'submission'};
                   1288:                     # We have to be careful with user supplied input.
                   1289:                     # most of the time we are okay because it is escaped.
                   1290:                     # However, there is one wrinkle: submissions which end in
                   1291:                     # and odd number of '\' cause insert errors to occur.  
                   1292:                     # Best trap this somehow...
                   1293:                     $submission = $dbh->quote($submission);
                   1294:                     $store_command .= "('".
                   1295:                         join("','",$symb_id,$part_id,
                   1296:                              $resp_id,$student_id,
                   1297:                              $transaction,
                   1298:                              $data->{'awarddetail'},
                   1299:                              $data->{'response_specific'},
                   1300:                              $data->{'response_specific_value'}).
                   1301:                              "',".$submission."),";
1.89      matthew  1302:                     $store_rows++;
                   1303:                 }
                   1304:             }
                   1305:         }
                   1306:     }
                   1307:     if ($store_rows) {
                   1308:         chop($store_command);
                   1309:         $dbh->do($store_command);
                   1310:         if ($dbh->err) {
                   1311:             $returnstatus = 'error storing response data';
                   1312:             &Apache::lonnet::logthis('insert error '.$dbh->errstr());
                   1313:             &Apache::lonnet::logthis("While attempting\n".$store_command);
                   1314:         }
                   1315:     }
                   1316:     ##
                   1317:     ## Update the students "current" data in the performance 
                   1318:     ## and parameters tables.
                   1319:     my ($status,undef) = &store_student_data
                   1320:         ($sname,$sdom,$courseid,
                   1321:          &Apache::lonnet::convert_dump_to_currentdump(\%studentdata));
                   1322:     if ($returnstatus eq 'okay' && $status ne 'okay') {
                   1323:         $returnstatus = 'error storing current data:'.$status;
                   1324:     } elsif ($status ne 'okay') {
                   1325:         $returnstatus .= ' error storing current data:'.$status;
                   1326:     }        
                   1327:     ##
                   1328:     ## Update the students time......
                   1329:     if ($returnstatus eq 'okay') {
1.113     matthew  1330:         &store_updatetime($student_id,$time_of_retrieval,$time_of_retrieval);
                   1331:         if ($dbh->err) {
                   1332:             if ($returnstatus eq 'okay') {
                   1333:                 $returnstatus = 'error updating student time';
                   1334:             } else {
                   1335:                 $returnstatus = 'error updating student time';
                   1336:             }
                   1337:         }
1.89      matthew  1338:     }
                   1339:     return $returnstatus;
                   1340: }
                   1341: 
                   1342: ################################################
                   1343: ################################################
                   1344: 
                   1345: =pod
                   1346: 
1.57      matthew  1347: =item &update_student_data()
                   1348: 
                   1349: Input: $sname, $sdom, $courseid
                   1350: 
                   1351: Output: $returnstatus, \%student_data
                   1352: 
                   1353: $returnstatus is a string describing any errors that occured.  'okay' is the
                   1354: default.
                   1355: \%student_data is the data returned by a call to lonnet::currentdump.
                   1356: 
                   1357: This subroutine loads a students data using lonnet::currentdump and inserts
                   1358: it into the MySQL database.  The inserts are done on two tables, 
                   1359: $performance_table and $parameters_table.  $parameters_table holds the data 
                   1360: that is not included in $performance_table.  See the description of 
                   1361: $performance_table elsewhere in this file.  The INSERT calls are made
                   1362: directly by this subroutine, not through lonmysql because we do a 'bulk'
                   1363: insert which takes advantage of MySQLs non-SQL compliant INSERT command to 
                   1364: insert multiple rows at a time.  If anything has gone wrong during this
                   1365: process, $returnstatus is updated with a description of the error and
                   1366: \%student_data is returned.  
                   1367: 
                   1368: Notice we do not insert the data and immediately query it.  This means it
                   1369: is possible for there to be data returned this first time that is not 
                   1370: available the second time.  CYA.
                   1371: 
                   1372: =cut
                   1373: 
                   1374: ################################################
                   1375: ################################################
                   1376: sub update_student_data {
                   1377:     my ($sname,$sdom,$courseid) = @_;
                   1378:     #
1.60      matthew  1379:     # Set up database names
                   1380:     &setup_table_names($courseid);
                   1381:     #
1.57      matthew  1382:     my $student_id = &get_student_id($sname,$sdom);
                   1383:     my $student = $sname.':'.$sdom;
                   1384:     #
                   1385:     my $returnstatus = 'okay';
                   1386:     #
                   1387:     # Download students data
                   1388:     my $time_of_retrieval = time;
                   1389:     my @tmp = &Apache::lonnet::currentdump($courseid,$sdom,$sname);
                   1390:     if ((scalar(@tmp) > 0) && ($tmp[0] =~ /^error:/)) {
                   1391:         &Apache::lonnet::logthis('error getting data for '.
                   1392:                                  $sname.':'.$sdom.' in course '.$courseid.
                   1393:                                  ':'.$tmp[0]);
                   1394:         $returnstatus = 'error getting data';
1.79      matthew  1395:         return ($returnstatus,undef);
1.57      matthew  1396:     }
                   1397:     if (scalar(@tmp) < 1) {
                   1398:         return ('no data',undef);
                   1399:     }
                   1400:     my %student_data = @tmp;
1.89      matthew  1401:     my @Results = &store_student_data($sname,$sdom,$courseid,\%student_data);
                   1402:     #
                   1403:     # Set the students update time
1.96      matthew  1404:     if ($Results[0] eq 'okay') {
1.113     matthew  1405:         &store_updatetime($student_id,$time_of_retrieval,$time_of_retrieval);
1.95      matthew  1406:     }
1.89      matthew  1407:     #
                   1408:     return @Results;
                   1409: }
                   1410: 
1.113     matthew  1411: sub store_updatetime {
                   1412:     my ($student_id,$updatetime,$fullupdatetime)=@_;
                   1413:     my $values = '';
                   1414:     if (defined($updatetime)) {
                   1415:         $values = 'updatetime='.$updatetime.' ';
                   1416:     }
                   1417:     if (defined($fullupdatetime)) {
                   1418:         if ($values ne '') {
                   1419:             $values .= ',';
                   1420:         }
                   1421:         $values .= 'fullupdatetime='.$fullupdatetime.' ';
                   1422:     }
                   1423:     return if ($values eq '');
                   1424:     my $dbh = &Apache::lonmysql::get_dbh();
                   1425:     my $request = 'UPDATE '.$student_table.' SET '.$values.
                   1426:         ' WHERE student_id='.$student_id.' LIMIT 1';
                   1427:     $dbh->do($request);
                   1428: }
                   1429: 
1.89      matthew  1430: sub store_student_data {
                   1431:     my ($sname,$sdom,$courseid,$student_data) = @_;
                   1432:     #
                   1433:     my $student_id = &get_student_id($sname,$sdom);
                   1434:     my $student = $sname.':'.$sdom;
                   1435:     #
                   1436:     my $returnstatus = 'okay';
1.57      matthew  1437:     #
                   1438:     # Remove all of the students data from the table
1.60      matthew  1439:     my $dbh = &Apache::lonmysql::get_dbh();
                   1440:     $dbh->do('DELETE FROM '.$performance_table.' WHERE student_id='.
                   1441:              $student_id);
                   1442:     $dbh->do('DELETE FROM '.$parameters_table.' WHERE student_id='.
                   1443:              $student_id);
1.57      matthew  1444:     #
                   1445:     # Store away the data
                   1446:     #
                   1447:     my $starttime = Time::HiRes::time;
                   1448:     my $elapsed = 0;
                   1449:     my $rows_stored;
1.98      matthew  1450:     my $store_parameters_command  = 'INSERT IGNORE INTO '.$parameters_table.
1.60      matthew  1451:         ' VALUES '."\n";
1.61      matthew  1452:     my $num_parameters = 0;
1.98      matthew  1453:     my $store_performance_command = 'INSERT IGNORE INTO '.$performance_table.
1.60      matthew  1454:         ' VALUES '."\n";
1.79      matthew  1455:     return ('error',undef) if (! defined($dbh));
1.89      matthew  1456:     while (my ($current_symb,$param_hash) = each(%{$student_data})) {
1.57      matthew  1457:         #
                   1458:         # make sure the symb is set up properly
                   1459:         my $symb_id = &get_symb_id($current_symb);
                   1460:         #
                   1461:         # Load data into the tables
1.63      matthew  1462:         while (my ($parameter,$value) = each(%$param_hash)) {
1.57      matthew  1463:             my $newstring;
1.63      matthew  1464:             if ($parameter !~ /(timestamp|resource\.(.*)\.(solved|tries|awarded|award|awarddetail|previous))/) {
1.57      matthew  1465:                 $newstring = "('".join("','",
                   1466:                                        $symb_id,$student_id,
1.69      matthew  1467:                                        $parameter)."',".
                   1468:                                            $dbh->quote($value)."),\n";
1.61      matthew  1469:                 $num_parameters ++;
1.57      matthew  1470:                 if ($newstring !~ /''/) {
                   1471:                     $store_parameters_command .= $newstring;
                   1472:                     $rows_stored++;
                   1473:                 }
                   1474:             }
                   1475:             next if ($parameter !~ /^resource\.(.*)\.solved$/);
                   1476:             #
                   1477:             my $part = $1;
                   1478:             my $part_id = &get_part_id($part);
                   1479:             next if (!defined($part_id));
                   1480:             my $solved  = $value;
                   1481:             my $tries   = $param_hash->{'resource.'.$part.'.tries'};
                   1482:             my $awarded = $param_hash->{'resource.'.$part.'.awarded'};
                   1483:             my $award   = $param_hash->{'resource.'.$part.'.award'};
                   1484:             my $awarddetail = $param_hash->{'resource.'.$part.'.awarddetail'};
                   1485:             my $timestamp = $param_hash->{'timestamp'};
1.60      matthew  1486:             #
1.74      matthew  1487:             $solved      = '' if (! defined($solved));
1.57      matthew  1488:             $tries       = '' if (! defined($tries));
                   1489:             $awarded     = '' if (! defined($awarded));
                   1490:             $award       = '' if (! defined($award));
                   1491:             $awarddetail = '' if (! defined($awarddetail));
1.73      matthew  1492:             $newstring = "('".join("','",$symb_id,$student_id,$part_id,$part,
1.57      matthew  1493:                                    $solved,$tries,$awarded,$award,
1.63      matthew  1494:                                    $awarddetail,$timestamp)."'),\n";
1.57      matthew  1495:             $store_performance_command .= $newstring;
                   1496:             $rows_stored++;
                   1497:         }
                   1498:     }
                   1499:     chop $store_parameters_command;
1.60      matthew  1500:     chop $store_parameters_command;
                   1501:     chop $store_performance_command;
1.57      matthew  1502:     chop $store_performance_command;
                   1503:     my $start = Time::HiRes::time;
1.94      matthew  1504:     $dbh->do($store_performance_command);
                   1505:     if ($dbh->err()) {
                   1506:         &Apache::lonnet::logthis(' bigass insert error:'.$dbh->errstr());
                   1507:         &Apache::lonnet::logthis('command = '.$store_performance_command);
                   1508:         $returnstatus = 'error: unable to insert performance into database';
                   1509:         return ($returnstatus,$student_data);
                   1510:     }
1.61      matthew  1511:     $dbh->do($store_parameters_command) if ($num_parameters>0);
1.57      matthew  1512:     if ($dbh->err()) {
                   1513:         &Apache::lonnet::logthis(' bigass insert error:'.$dbh->errstr());
1.61      matthew  1514:         &Apache::lonnet::logthis('command = '.$store_parameters_command);
1.87      matthew  1515:         &Apache::lonnet::logthis('rows_stored = '.$rows_stored);
                   1516:         &Apache::lonnet::logthis('student_id = '.$student_id);
1.57      matthew  1517:         $returnstatus = 'error: unable to insert parameters into database';
1.89      matthew  1518:         return ($returnstatus,$student_data);
1.57      matthew  1519:     }
                   1520:     $elapsed += Time::HiRes::time - $start;
1.89      matthew  1521:     return ($returnstatus,$student_data);
1.57      matthew  1522: }
                   1523: 
1.89      matthew  1524: ######################################
                   1525: ######################################
1.57      matthew  1526: 
                   1527: =pod
                   1528: 
1.89      matthew  1529: =item &ensure_tables_are_set_up($courseid)
1.57      matthew  1530: 
1.89      matthew  1531: Checks to be sure the MySQL tables for the given class are set up.
                   1532: If $courseid is omitted it will be obtained from the environment.
1.57      matthew  1533: 
1.89      matthew  1534: Returns nothing on success and 'error' on failure
1.57      matthew  1535: 
                   1536: =cut
                   1537: 
1.89      matthew  1538: ######################################
                   1539: ######################################
                   1540: sub ensure_tables_are_set_up {
                   1541:     my ($courseid) = @_;
1.61      matthew  1542:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
                   1543:     # 
                   1544:     # Clean out package variables
1.57      matthew  1545:     &setup_table_names($courseid);
                   1546:     #
                   1547:     # if the tables do not exist, make them
                   1548:     my @CurrentTable = &Apache::lonmysql::tables_in_db();
1.113     matthew  1549:     my ($found_symb,$found_student,$found_part,
1.89      matthew  1550:         $found_performance,$found_parameters,$found_fulldump_part,
                   1551:         $found_fulldump_response,$found_fulldump_timestamp);
1.57      matthew  1552:     foreach (@CurrentTable) {
                   1553:         $found_symb        = 1 if ($_ eq $symb_table);
                   1554:         $found_student     = 1 if ($_ eq $student_table);
                   1555:         $found_part        = 1 if ($_ eq $part_table);
                   1556:         $found_performance = 1 if ($_ eq $performance_table);
                   1557:         $found_parameters  = 1 if ($_ eq $parameters_table);
1.89      matthew  1558:         $found_fulldump_part      = 1 if ($_ eq $fulldump_part_table);
                   1559:         $found_fulldump_response  = 1 if ($_ eq $fulldump_response_table);
                   1560:         $found_fulldump_timestamp = 1 if ($_ eq $fulldump_timestamp_table);
1.57      matthew  1561:     }
1.113     matthew  1562:     if (!$found_symb        || 
1.57      matthew  1563:         !$found_student     || !$found_part   ||
1.89      matthew  1564:         !$found_performance || !$found_parameters ||
                   1565:         !$found_fulldump_part || !$found_fulldump_response ||
                   1566:         !$found_fulldump_timestamp ) {
1.57      matthew  1567:         if (&init_dbs($courseid)) {
1.89      matthew  1568:             return 'error';
1.57      matthew  1569:         }
                   1570:     }
1.89      matthew  1571: }
                   1572: 
                   1573: ################################################
                   1574: ################################################
                   1575: 
                   1576: =pod
                   1577: 
                   1578: =item &ensure_current_data()
                   1579: 
                   1580: Input: $sname, $sdom, $courseid
                   1581: 
                   1582: Output: $status, $data
                   1583: 
                   1584: This routine ensures the data for a given student is up to date.
1.113     matthew  1585: The $student_table is queried to determine the time of the last update.  
1.89      matthew  1586: If the students data is out of date, &update_student_data() is called.  
                   1587: The return values from the call to &update_student_data() are returned.
                   1588: 
                   1589: =cut
                   1590: 
                   1591: ################################################
                   1592: ################################################
                   1593: sub ensure_current_data {
                   1594:     my ($sname,$sdom,$courseid) = @_;
                   1595:     my $status = 'okay';   # return value
                   1596:     #
                   1597:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
                   1598:     &ensure_tables_are_set_up($courseid);
1.57      matthew  1599:     #
                   1600:     # Get the update time for the user
                   1601:     my $updatetime = 0;
1.60      matthew  1602:     my $modifiedtime = &Apache::lonnet::GetFileTimestamp
                   1603:         ($sdom,$sname,$courseid.'.db',
                   1604:          $Apache::lonnet::perlvar{'lonUsersDir'});
1.57      matthew  1605:     #
1.87      matthew  1606:     my $student_id = &get_student_id($sname,$sdom);
1.113     matthew  1607:     my @Result = &Apache::lonmysql::get_rows($student_table,
1.87      matthew  1608:                                              "student_id ='$student_id'");
1.57      matthew  1609:     my $data = undef;
                   1610:     if (@Result) {
1.113     matthew  1611:         $updatetime = $Result[0]->[5];  # Ack!  This is dumb!
1.57      matthew  1612:     }
                   1613:     if ($modifiedtime > $updatetime) {
                   1614:         ($status,$data) = &update_student_data($sname,$sdom,$courseid);
                   1615:     }
                   1616:     return ($status,$data);
                   1617: }
                   1618: 
                   1619: ################################################
                   1620: ################################################
                   1621: 
                   1622: =pod
                   1623: 
1.89      matthew  1624: =item &ensure_current_full_data($sname,$sdom,$courseid)
                   1625: 
                   1626: Input: $sname, $sdom, $courseid
                   1627: 
                   1628: Output: $status
                   1629: 
                   1630: This routine ensures the fulldata (the data from a lonnet::dump, not a
                   1631: lonnet::currentdump) for a given student is up to date.
1.113     matthew  1632: The $student_table is queried to determine the time of the last update.  
1.89      matthew  1633: If the students fulldata is out of date, &update_full_student_data() is
                   1634: called.  
                   1635: 
                   1636: The return value from the call to &update_full_student_data() is returned.
                   1637: 
                   1638: =cut
                   1639: 
                   1640: ################################################
                   1641: ################################################
                   1642: sub ensure_current_full_data {
                   1643:     my ($sname,$sdom,$courseid) = @_;
                   1644:     my $status = 'okay';   # return value
                   1645:     #
                   1646:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
                   1647:     &ensure_tables_are_set_up($courseid);
                   1648:     #
                   1649:     # Get the update time for the user
                   1650:     my $modifiedtime = &Apache::lonnet::GetFileTimestamp
                   1651:         ($sdom,$sname,$courseid.'.db',
                   1652:          $Apache::lonnet::perlvar{'lonUsersDir'});
                   1653:     #
                   1654:     my $student_id = &get_student_id($sname,$sdom);
1.113     matthew  1655:     my @Result = &Apache::lonmysql::get_rows($student_table,
1.89      matthew  1656:                                              "student_id ='$student_id'");
                   1657:     my $updatetime;
                   1658:     if (@Result && ref($Result[0]) eq 'ARRAY') {
1.113     matthew  1659:         $updatetime = $Result[0]->[6];
1.89      matthew  1660:     }
                   1661:     if (! defined($updatetime) || $modifiedtime > $updatetime) {
                   1662:         $status = &update_full_student_data($sname,$sdom,$courseid);
                   1663:     }
                   1664:     return $status;
                   1665: }
                   1666: 
                   1667: ################################################
                   1668: ################################################
                   1669: 
                   1670: =pod
                   1671: 
1.57      matthew  1672: =item &get_student_data_from_performance_cache()
                   1673: 
                   1674: Input: $sname, $sdom, $symb, $courseid
                   1675: 
                   1676: Output: hash reference containing the data for the given student.
                   1677: If $symb is undef, all the students data is returned.
                   1678: 
                   1679: This routine is the heart of the local caching system.  See the description
                   1680: of $performance_table, $symb_table, $student_table, and $part_table.  The
                   1681: main task is building the MySQL request.  The tables appear in the request
                   1682: in the order in which they should be parsed by MySQL.  When searching
                   1683: on a student the $student_table is used to locate the 'student_id'.  All
                   1684: rows in $performance_table which have a matching 'student_id' are returned,
                   1685: with data from $part_table and $symb_table which match the entries in
                   1686: $performance_table, 'part_id' and 'symb_id'.  When searching on a symb,
                   1687: the $symb_table is processed first, with matching rows grabbed from 
                   1688: $performance_table and filled in from $part_table and $student_table in
                   1689: that order.  
                   1690: 
                   1691: Running 'EXPLAIN ' on the 'SELECT' statements generated can be quite 
                   1692: interesting, especially if you play with the order the tables are listed.  
                   1693: 
                   1694: =cut
                   1695: 
                   1696: ################################################
                   1697: ################################################
                   1698: sub get_student_data_from_performance_cache {
                   1699:     my ($sname,$sdom,$symb,$courseid)=@_;
                   1700:     my $student = $sname.':'.$sdom if (defined($sname) && defined($sdom));
1.61      matthew  1701:     &setup_table_names($courseid);
1.57      matthew  1702:     #
                   1703:     # Return hash
                   1704:     my $studentdata;
                   1705:     #
                   1706:     my $dbh = &Apache::lonmysql::get_dbh();
                   1707:     my $request = "SELECT ".
1.73      matthew  1708:         "d.symb,a.part,a.solved,a.tries,a.awarded,a.award,a.awarddetail,".
1.63      matthew  1709:             "a.timestamp ";
1.57      matthew  1710:     if (defined($student)) {
                   1711:         $request .= "FROM $student_table AS b ".
                   1712:             "LEFT JOIN $performance_table AS a ON b.student_id=a.student_id ".
1.73      matthew  1713: #            "LEFT JOIN $part_table AS c ON c.part_id = a.part_id ".
1.57      matthew  1714:             "LEFT JOIN $symb_table AS d ON d.symb_id = a.symb_id ".
                   1715:                 "WHERE student='$student'";
                   1716:         if (defined($symb) && $symb ne '') {
1.67      matthew  1717:             $request .= " AND d.symb=".$dbh->quote($symb);
1.57      matthew  1718:         }
                   1719:     } elsif (defined($symb) && $symb ne '') {
                   1720:         $request .= "FROM $symb_table as d ".
                   1721:             "LEFT JOIN $performance_table AS a ON d.symb_id=a.symb_id ".
1.73      matthew  1722: #            "LEFT JOIN $part_table    AS c ON c.part_id = a.part_id ".
1.57      matthew  1723:             "LEFT JOIN $student_table AS b ON b.student_id = a.student_id ".
                   1724:                 "WHERE symb='".$dbh->quote($symb)."'";
                   1725:     }
                   1726:     my $starttime = Time::HiRes::time;
                   1727:     my $rows_retrieved = 0;
                   1728:     my $sth = $dbh->prepare($request);
                   1729:     $sth->execute();
                   1730:     if ($sth->err()) {
                   1731:         &Apache::lonnet::logthis("Unable to execute MySQL request:");
                   1732:         &Apache::lonnet::logthis("\n".$request."\n");
                   1733:         &Apache::lonnet::logthis("error is:".$sth->errstr());
                   1734:         return undef;
                   1735:     }
                   1736:     foreach my $row (@{$sth->fetchall_arrayref}) {
                   1737:         $rows_retrieved++;
1.63      matthew  1738:         my ($symb,$part,$solved,$tries,$awarded,$award,$awarddetail,$time) = 
1.57      matthew  1739:             (@$row);
                   1740:         my $base = 'resource.'.$part;
                   1741:         $studentdata->{$symb}->{$base.'.solved'}  = $solved;
                   1742:         $studentdata->{$symb}->{$base.'.tries'}   = $tries;
                   1743:         $studentdata->{$symb}->{$base.'.awarded'} = $awarded;
                   1744:         $studentdata->{$symb}->{$base.'.award'}   = $award;
                   1745:         $studentdata->{$symb}->{$base.'.awarddetail'} = $awarddetail;
                   1746:         $studentdata->{$symb}->{'timestamp'} = $time if (defined($time) && $time ne '');
1.67      matthew  1747:     }
1.97      matthew  1748:     ## Get misc parameters
                   1749:     $request = 'SELECT c.symb,a.parameter,a.value '.
                   1750:         "FROM $student_table AS b ".
                   1751:         "LEFT JOIN $parameters_table AS a ON b.student_id=a.student_id ".
                   1752:         "LEFT JOIN $symb_table AS c ON c.symb_id = a.symb_id ".
                   1753:         "WHERE student='$student'";
                   1754:     if (defined($symb) && $symb ne '') {
                   1755:         $request .= " AND c.symb=".$dbh->quote($symb);
                   1756:     }
                   1757:     $sth = $dbh->prepare($request);
                   1758:     $sth->execute();
                   1759:     if ($sth->err()) {
                   1760:         &Apache::lonnet::logthis("Unable to execute MySQL request:");
                   1761:         &Apache::lonnet::logthis("\n".$request."\n");
                   1762:         &Apache::lonnet::logthis("error is:".$sth->errstr());
                   1763:         if (defined($symb) && $symb ne '') {
                   1764:             $studentdata = $studentdata->{$symb};
                   1765:         }
                   1766:         return $studentdata;
                   1767:     }
                   1768:     #
                   1769:     foreach my $row (@{$sth->fetchall_arrayref}) {
                   1770:         $rows_retrieved++;
                   1771:         my ($symb,$parameter,$value) = (@$row);
                   1772:         $studentdata->{$symb}->{$parameter}  = $value;
                   1773:     }
                   1774:     #
1.67      matthew  1775:     if (defined($symb) && $symb ne '') {
                   1776:         $studentdata = $studentdata->{$symb};
1.57      matthew  1777:     }
                   1778:     return $studentdata;
                   1779: }
                   1780: 
                   1781: ################################################
                   1782: ################################################
                   1783: 
                   1784: =pod
                   1785: 
                   1786: =item &get_current_state()
                   1787: 
                   1788: Input: $sname,$sdom,$symb,$courseid
                   1789: 
                   1790: Output: Described below
1.46      matthew  1791: 
1.47      matthew  1792: Retrieve the current status of a students performance.  $sname and
1.46      matthew  1793: $sdom are the only required parameters.  If $symb is undef the results
1.47      matthew  1794: of an &Apache::lonnet::currentdump() will be returned.  
1.46      matthew  1795: If $courseid is undef it will be retrieved from the environment.
                   1796: 
                   1797: The return structure is based on &Apache::lonnet::currentdump.  If
                   1798: $symb is unspecified, all the students data is returned in a hash of
                   1799: the form:
                   1800: ( 
                   1801:   symb1 => { param1 => value1, param2 => value2 ... },
                   1802:   symb2 => { param1 => value1, param2 => value2 ... },
                   1803: )
                   1804: 
                   1805: If $symb is specified, a hash of 
                   1806: (
                   1807:   param1 => value1, 
                   1808:   param2 => value2,
                   1809: )
                   1810: is returned.
                   1811: 
1.57      matthew  1812: If no data is found for $symb, or if the student has no performance data,
1.46      matthew  1813: an empty list is returned.
                   1814: 
                   1815: =cut
                   1816: 
                   1817: ################################################
                   1818: ################################################
                   1819: sub get_current_state {
1.47      matthew  1820:     my ($sname,$sdom,$symb,$courseid,$forcedownload)=@_;
                   1821:     #
1.46      matthew  1822:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
1.47      matthew  1823:     #
1.61      matthew  1824:     return () if (! defined($sname) || ! defined($sdom));
                   1825:     #
1.57      matthew  1826:     my ($status,$data) = &ensure_current_data($sname,$sdom,$courseid);
1.77      matthew  1827: #    &Apache::lonnet::logthis
                   1828: #        ('sname = '.$sname.
                   1829: #         ' domain = '.$sdom.
                   1830: #         ' status = '.$status.
                   1831: #         ' data is '.(defined($data)?'defined':'undefined'));
1.73      matthew  1832: #    while (my ($symb,$hash) = each(%$data)) {
                   1833: #        &Apache::lonnet::logthis($symb."\n----------------------------------");
                   1834: #        while (my ($key,$value) = each (%$hash)) {
                   1835: #            &Apache::lonnet::logthis("   ".$key." = ".$value);
                   1836: #        }
                   1837: #    }
1.47      matthew  1838:     #
1.79      matthew  1839:     if (defined($data) && defined($symb) && ref($data->{$symb})) {
                   1840:         return %{$data->{$symb}};
                   1841:     } elsif (defined($data) && ! defined($symb) && ref($data)) {
                   1842:         return %$data;
                   1843:     } 
                   1844:     if ($status eq 'no data') {
1.57      matthew  1845:         return ();
                   1846:     } else {
                   1847:         if ($status ne 'okay' && $status ne '') {
                   1848:             &Apache::lonnet::logthis('status = '.$status);
1.47      matthew  1849:             return ();
                   1850:         }
1.57      matthew  1851:         my $returnhash = &get_student_data_from_performance_cache($sname,$sdom,
                   1852:                                                       $symb,$courseid);
                   1853:         return %$returnhash if (defined($returnhash));
1.46      matthew  1854:     }
1.57      matthew  1855:     return ();
1.61      matthew  1856: }
                   1857: 
                   1858: ################################################
                   1859: ################################################
                   1860: 
                   1861: =pod
                   1862: 
                   1863: =item &get_problem_statistics()
                   1864: 
                   1865: Gather data on a given problem.  The database is assumed to be 
                   1866: populated and all local caching variables are assumed to be set
                   1867: properly.  This means you need to call &ensure_current_data for
                   1868: the students you are concerned with prior to calling this routine.
                   1869: 
1.124     matthew  1870: Inputs: $Sections, $status, $symb, $part, $courseid, $starttime, $endtime
1.61      matthew  1871: 
1.64      matthew  1872: =over 4
                   1873: 
1.124     matthew  1874: =item $Sections Array ref containing section names for students.  
                   1875: 'all' is allowed to be the first (and only) item in the array.
                   1876: 
                   1877: =item $status String describing the status of students
1.64      matthew  1878: 
                   1879: =item $symb is the symb for the problem.
                   1880: 
                   1881: =item $part is the part id you need statistics for
                   1882: 
                   1883: =item $courseid is the course id, of course!
                   1884: 
1.122     matthew  1885: =item $starttime and $endtime are unix times which to use to limit
                   1886: the statistical data.
                   1887: 
1.64      matthew  1888: =back
                   1889: 
1.66      matthew  1890: Outputs: See the code for up to date information.  A hash reference is
                   1891: returned.  The hash has the following keys defined:
1.64      matthew  1892: 
                   1893: =over 4
                   1894: 
1.66      matthew  1895: =item num_students The number of students attempting the problem
                   1896:       
                   1897: =item tries The total number of tries for the students
                   1898:       
                   1899: =item max_tries The maximum number of tries taken
                   1900:       
                   1901: =item mean_tries The average number of tries
                   1902:       
                   1903: =item num_solved The number of students able to solve the problem
                   1904:       
                   1905: =item num_override The number of students whose answer is 'correct_by_override'
                   1906:       
                   1907: =item deg_of_diff The degree of difficulty of the problem
                   1908:       
                   1909: =item std_tries The standard deviation of the number of tries
                   1910:       
                   1911: =item skew_tries The skew of the number of tries
1.64      matthew  1912: 
1.66      matthew  1913: =item per_wrong The number of students attempting the problem who were not
                   1914: able to answer it correctly.
1.64      matthew  1915: 
                   1916: =back
                   1917: 
1.61      matthew  1918: =cut
                   1919: 
                   1920: ################################################
                   1921: ################################################
                   1922: sub get_problem_statistics {
1.122     matthew  1923:     my ($Sections,$status,$symb,$part,$courseid,$starttime,$endtime) = @_;
1.61      matthew  1924:     return if (! defined($symb) || ! defined($part));
                   1925:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
                   1926:     #
1.100     matthew  1927:     &setup_table_names($courseid);
1.61      matthew  1928:     my $symb_id = &get_symb_id($symb);
                   1929:     my $part_id = &get_part_id($part);
                   1930:     my $stats_table = $courseid.'_problem_stats';
                   1931:     #
                   1932:     my $dbh = &Apache::lonmysql::get_dbh();
                   1933:     return undef if (! defined($dbh));
                   1934:     #
1.123     matthew  1935:     # Clean out the table
1.61      matthew  1936:     $dbh->do('DROP TABLE '.$stats_table);  # May return an error
                   1937:     my $request = 
1.115     matthew  1938:         'CREATE TEMPORARY TABLE '.$stats_table.' '.
                   1939:         'SELECT a.student_id,a.solved,a.award,a.awarded,a.tries '.
                   1940:         'FROM '.$performance_table.' AS a ';
1.123     matthew  1941:     #
                   1942:     # See if we need to include some requirements on the students
1.115     matthew  1943:     if ((defined($Sections) && lc($Sections->[0]) ne 'all') || 
                   1944:         (defined($status)   && lc($status)        ne 'any')) {
                   1945:         $request .= 'NATURAL LEFT JOIN '.$student_table.' AS b ';
                   1946:     }
                   1947:     $request .= ' WHERE a.symb_id='.$symb_id.' AND a.part_id='.$part_id;
1.123     matthew  1948:     #
                   1949:     # Limit the students included to those specified
1.115     matthew  1950:     if (defined($Sections) && lc($Sections->[0]) ne 'all') {
1.64      matthew  1951:         $request .= ' AND ('.
1.115     matthew  1952:             join(' OR ', map { "b.section='".$_."'" } @$Sections
1.64      matthew  1953:                  ).')';
                   1954:     }
1.115     matthew  1955:     if (defined($status) && lc($status) ne 'any') {
                   1956:         $request .= " AND b.status='".$status."'";
1.122     matthew  1957:     }
                   1958:     #
1.123     matthew  1959:     # Limit by starttime and endtime
1.122     matthew  1960:     my $time_requirements = undef;
                   1961:     if (defined($starttime)) {
                   1962:         $time_requirements .= 'a.timestamp>='.$starttime;
                   1963:         if (defined($endtime)) {
                   1964:             $time_requirements .= ' AND a.timestamp<='.$endtime;
                   1965:         }
                   1966:     } elsif (defined($endtime)) {
                   1967:         $time_requirements .= 'a.timestamp<='.$endtime;
                   1968:     }
                   1969:     if (defined($time_requirements)) {
                   1970:         $request .= ' AND '.$time_requirements;
1.115     matthew  1971:     }
1.123     matthew  1972:     #
                   1973:     # Finally, execute the request to create the temporary table
1.61      matthew  1974:     $dbh->do($request);
1.123     matthew  1975:     #
                   1976:     # Collect the first suite of statistics
1.109     matthew  1977:     $request = 'SELECT COUNT(*),SUM(tries),MAX(tries),AVG(tries),STD(tries) '.
                   1978:         'FROM '.$stats_table;
1.61      matthew  1979:     my ($num,$tries,$mod,$mean,$STD) = &execute_SQL_request
1.109     matthew  1980:         ($dbh,$request);
                   1981:     $request = 'SELECT SUM(awarded) FROM '.$stats_table;
                   1982:     my ($Solved) = &execute_SQL_request($dbh,$request);
                   1983:     $request = 'SELECT SUM(awarded) FROM '.$stats_table.
                   1984:         " WHERE solved='correct_by_override'";
                   1985:     my ($solved) = &execute_SQL_request($dbh,$request);
                   1986:     #
1.61      matthew  1987:     $num    = 0 if (! defined($num));
                   1988:     $tries  = 0 if (! defined($tries));
                   1989:     $mod    = 0 if (! defined($mod));
                   1990:     $STD    = 0 if (! defined($STD));
                   1991:     $Solved = 0 if (! defined($Solved));
                   1992:     $solved = 0 if (! defined($solved));
                   1993:     #
1.123     matthew  1994:     # Compute the more complicated statistics
1.61      matthew  1995:     my $DegOfDiff = 'nan';
1.66      matthew  1996:     $DegOfDiff = 1-($Solved)/$tries if ($tries>0);
1.123     matthew  1997:     #
1.61      matthew  1998:     my $SKEW = 'nan';
1.66      matthew  1999:     my $wrongpercent = 0;
1.61      matthew  2000:     if ($num > 0) {
                   2001:         ($SKEW) = &execute_SQL_request($dbh,'SELECT SQRT(SUM('.
                   2002:                                      'POWER(tries - '.$STD.',3)'.
                   2003:                                      '))/'.$num.' FROM '.$stats_table);
1.66      matthew  2004:         $wrongpercent=int(10*100*($num-$Solved+$solved)/$num)/10;
1.61      matthew  2005:     }
                   2006:     #
1.123     matthew  2007:     # Drop the temporary table
                   2008:     $dbh->do('DROP TABLE '.$stats_table);  # May return an error
1.81      matthew  2009:     #
                   2010:     # Store in metadata
1.80      www      2011:     if ($num) {
                   2012: 	my %storestats=();
1.123     matthew  2013:         #
1.86      www      2014:         my $urlres=(&Apache::lonnet::decode_symb($symb))[2];
1.123     matthew  2015:         #
1.80      www      2016: 	$storestats{$courseid.'___'.$urlres.'___timestamp'}=time;       
                   2017: 	$storestats{$courseid.'___'.$urlres.'___stdno'}=$num;
                   2018: 	$storestats{$courseid.'___'.$urlres.'___avetries'}=$mean;	   
                   2019: 	$storestats{$courseid.'___'.$urlres.'___difficulty'}=$DegOfDiff;
1.123     matthew  2020:         #
1.80      www      2021: 	$urlres=~/^(\w+)\/(\w+)/; 
                   2022: 	&Apache::lonnet::put('nohist_resevaldata',\%storestats,$1,$2); 
                   2023:     }
1.81      matthew  2024:     #
                   2025:     # Return result
1.66      matthew  2026:     return { num_students => $num,
                   2027:              tries        => $tries,
                   2028:              max_tries    => $mod,
                   2029:              mean_tries   => $mean,
                   2030:              std_tries    => $STD,
                   2031:              skew_tries   => $SKEW,
                   2032:              num_solved   => $Solved,
                   2033:              num_override => $solved,
                   2034:              per_wrong    => $wrongpercent,
1.81      matthew  2035:              deg_of_diff  => $DegOfDiff };
1.61      matthew  2036: }
                   2037: 
                   2038: sub execute_SQL_request {
                   2039:     my ($dbh,$request)=@_;
                   2040: #    &Apache::lonnet::logthis($request);
                   2041:     my $sth = $dbh->prepare($request);
                   2042:     $sth->execute();
                   2043:     my $row = $sth->fetchrow_arrayref();
                   2044:     if (ref($row) eq 'ARRAY' && scalar(@$row)>0) {
                   2045:         return @$row;
                   2046:     }
                   2047:     return ();
                   2048: }
1.123     matthew  2049: 
1.61      matthew  2050: 
1.105     matthew  2051: sub get_student_data {
                   2052:     my ($students,$courseid) = @_;
                   2053:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
                   2054:     &setup_table_names($courseid);
                   2055:     my $dbh = &Apache::lonmysql::get_dbh();
                   2056:     return undef if (! defined($dbh));
                   2057:     my $request = 'SELECT '.
                   2058:         'student_id, student '.
                   2059:         'FROM '.$student_table;
                   2060:     if (defined($students)) {
                   2061:         $request .= ' WHERE ('.
                   2062:             join(' OR ', map {'student_id='.
                   2063:                                   &get_student_id($_->{'username'},
                   2064:                                                   $_->{'domain'})
                   2065:                               } @$students
                   2066:                  ).')';
                   2067:     }
                   2068:     $request.= ' ORDER BY student_id';
                   2069:     my $sth = $dbh->prepare($request);
                   2070:     $sth->execute();
                   2071:     if ($dbh->err) {
                   2072:         &Apache::lonnet::logthis('error = '.$dbh->errstr());
                   2073:         return undef;
                   2074:     }
                   2075:     my $dataset = $sth->fetchall_arrayref();
                   2076:     if (ref($dataset) eq 'ARRAY' && scalar(@$dataset)>0) {
                   2077:         return $dataset;
                   2078:     }
                   2079: }
                   2080: 
1.108     matthew  2081: sub RD_student_id    { return 0; }
                   2082: sub RD_awarddetail   { return 1; }
                   2083: sub RD_response_eval { return 2; }
                   2084: sub RD_submission    { return 3; }
                   2085: sub RD_timestamp     { return 4; }
                   2086: sub RD_tries         { return 5; }
                   2087: sub RD_sname         { return 6; }
                   2088: 
                   2089: sub get_response_data {
1.100     matthew  2090:     my ($students,$symb,$response,$courseid) = @_;
1.103     matthew  2091:     return undef if (! defined($symb) || 
1.100     matthew  2092:                ! defined($response));
                   2093:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
                   2094:     #
                   2095:     &setup_table_names($courseid);
                   2096:     my $symb_id = &get_symb_id($symb);
                   2097:     my $response_id = &get_part_id($response);
                   2098:     #
                   2099:     my $dbh = &Apache::lonmysql::get_dbh();
                   2100:     return undef if (! defined($dbh));
                   2101:     my $request = 'SELECT '.
1.105     matthew  2102:         'a.student_id, a.awarddetail, a.response_specific_value, '.
1.108     matthew  2103:         'a.submission, b.timestamp, c.tries, d.student '.
1.100     matthew  2104:         'FROM '.$fulldump_response_table.' AS a '.
                   2105:         'LEFT JOIN '.$fulldump_timestamp_table.' AS b '.
                   2106:         'ON a.symb_id=b.symb_id AND a.student_id=b.student_id AND '.
                   2107:         'a.transaction = b.transaction '.
                   2108:         'LEFT JOIN '.$fulldump_part_table.' AS c '.
                   2109:         'ON a.symb_id=c.symb_id AND a.student_id=c.student_id AND '.        
                   2110:         'a.part_id=c.part_id AND a.transaction = c.transaction '.
1.108     matthew  2111:         'LEFT JOIN '.$student_table.' AS d '.
                   2112:         'ON a.student_id=d.student_id '.
1.100     matthew  2113:         'WHERE '.
                   2114:         'a.symb_id='.$symb_id.' AND a.response_id='.$response_id;
                   2115:     if (defined($students)) {
                   2116:         $request .= ' AND ('.
1.103     matthew  2117:             join(' OR ', map {'a.student_id='.
1.100     matthew  2118:                                   &get_student_id($_->{'username'},
                   2119:                                                   $_->{'domain'})
                   2120:                               } @$students
                   2121:                  ).')';
                   2122:     }
                   2123:     $request .= ' ORDER BY b.timestamp';
1.103     matthew  2124: #    &Apache::lonnet::logthis("request =\n".$request);
1.100     matthew  2125:     my $sth = $dbh->prepare($request);
                   2126:     $sth->execute();
1.105     matthew  2127:     if ($dbh->err) {
                   2128:         &Apache::lonnet::logthis('error = '.$dbh->errstr());
                   2129:         return undef;
                   2130:     }
1.100     matthew  2131:     my $dataset = $sth->fetchall_arrayref();
                   2132:     if (ref($dataset) eq 'ARRAY' && scalar(@$dataset)>0) {
1.117     matthew  2133:         # Clear the \'s from around the submission
                   2134:         for (my $i =0;$i<scalar(@$dataset);$i++) {
                   2135:             $dataset->[$i]->[3] =~ s/(\'$|^\')//g;
                   2136:         }
1.103     matthew  2137:         return $dataset;
1.100     matthew  2138:     }
1.118     matthew  2139: }
                   2140: 
                   2141: 
                   2142: sub RDs_awarddetail   { return 3; }
                   2143: sub RDs_submission    { return 2; }
                   2144: sub RDs_timestamp     { return 1; }
                   2145: sub RDs_tries         { return 0; }
1.119     matthew  2146: sub RDs_awarded       { return 4; }
1.118     matthew  2147: 
                   2148: sub get_response_data_by_student {
                   2149:     my ($student,$symb,$response,$courseid) = @_;
                   2150:     return undef if (! defined($symb) || 
                   2151:                      ! defined($response));
                   2152:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
                   2153:     #
                   2154:     &setup_table_names($courseid);
                   2155:     my $symb_id = &get_symb_id($symb);
                   2156:     my $response_id = &get_part_id($response);
                   2157:     #
                   2158:     my $student_id = &get_student_id($student->{'username'},
                   2159:                                      $student->{'domain'});
                   2160:     #
                   2161:     my $dbh = &Apache::lonmysql::get_dbh();
                   2162:     return undef if (! defined($dbh));
                   2163:     my $request = 'SELECT '.
1.119     matthew  2164:         'c.tries, b.timestamp, a.submission, a.awarddetail, e.awarded '.
1.118     matthew  2165:         'FROM '.$fulldump_response_table.' AS a '.
                   2166:         'LEFT JOIN '.$fulldump_timestamp_table.' AS b '.
                   2167:         'ON a.symb_id=b.symb_id AND a.student_id=b.student_id AND '.
                   2168:         'a.transaction = b.transaction '.
                   2169:         'LEFT JOIN '.$fulldump_part_table.' AS c '.
                   2170:         'ON a.symb_id=c.symb_id AND a.student_id=c.student_id AND '.        
                   2171:         'a.part_id=c.part_id AND a.transaction = c.transaction '.
                   2172:         'LEFT JOIN '.$student_table.' AS d '.
                   2173:         'ON a.student_id=d.student_id '.
1.119     matthew  2174:         'LEFT JOIN '.$performance_table.' AS e '.
                   2175:         'ON a.symb_id=e.symb_id AND a.part_id=e.part_id AND '.
                   2176:         'a.student_id=e.student_id AND c.tries=e.tries '.
1.118     matthew  2177:         'WHERE '.
                   2178:         'a.symb_id='.$symb_id.' AND a.response_id='.$response_id.
                   2179:         ' AND a.student_id='.$student_id.' ORDER BY b.timestamp';
1.125   ! matthew  2180: #    &Apache::lonnet::logthis("request =\n".$request);
1.118     matthew  2181:     my $sth = $dbh->prepare($request);
                   2182:     $sth->execute();
                   2183:     if ($dbh->err) {
                   2184:         &Apache::lonnet::logthis('error = '.$dbh->errstr());
                   2185:         return undef;
                   2186:     }
                   2187:     my $dataset = $sth->fetchall_arrayref();
                   2188:     if (ref($dataset) eq 'ARRAY' && scalar(@$dataset)>0) {
                   2189:         # Clear the \'s from around the submission
                   2190:         for (my $i =0;$i<scalar(@$dataset);$i++) {
                   2191:             $dataset->[$i]->[2] =~ s/(\'$|^\')//g;
                   2192:         }
                   2193:         return $dataset;
                   2194:     }
                   2195:     return undef; # error occurred
1.106     matthew  2196: }
1.108     matthew  2197: 
                   2198: sub RT_student_id { return 0; }
                   2199: sub RT_awarded    { return 1; }
                   2200: sub RT_tries      { return 2; }
                   2201: sub RT_timestamp  { return 3; }
1.106     matthew  2202: 
                   2203: sub get_response_time_data {
1.107     matthew  2204:     my ($students,$symb,$part,$courseid) = @_;
1.106     matthew  2205:     return undef if (! defined($symb) || 
1.107     matthew  2206:                      ! defined($part));
1.106     matthew  2207:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
                   2208:     #
                   2209:     &setup_table_names($courseid);
                   2210:     my $symb_id = &get_symb_id($symb);
1.107     matthew  2211:     my $part_id = &get_part_id($part);
1.106     matthew  2212:     #
                   2213:     my $dbh = &Apache::lonmysql::get_dbh();
                   2214:     return undef if (! defined($dbh));
                   2215:     my $request = 'SELECT '.
1.107     matthew  2216:         'a.student_id, a.awarded, a.tries, b.timestamp '.
                   2217:         'FROM '.$fulldump_part_table.' AS a '.
1.106     matthew  2218:         'NATURAL LEFT JOIN '.$fulldump_timestamp_table.' AS b '.
                   2219: #        'ON a.symb_id=b.symb_id AND a.student_id=b.student_id AND '.
                   2220: #        'a.transaction = b.transaction '.
                   2221:         'WHERE '.
1.107     matthew  2222:         'a.symb_id='.$symb_id.' AND a.part_id='.$part_id;
1.106     matthew  2223:     if (defined($students)) {
                   2224:         $request .= ' AND ('.
                   2225:             join(' OR ', map {'a.student_id='.
                   2226:                                   &get_student_id($_->{'username'},
                   2227:                                                   $_->{'domain'})
                   2228:                               } @$students
                   2229:                  ).')';
                   2230:     }
                   2231:     $request .= ' ORDER BY b.timestamp';
                   2232: #    &Apache::lonnet::logthis("request =\n".$request);
                   2233:     my $sth = $dbh->prepare($request);
                   2234:     $sth->execute();
                   2235:     if ($dbh->err) {
                   2236:         &Apache::lonnet::logthis('error = '.$dbh->errstr());
                   2237:         return undef;
                   2238:     }
                   2239:     my $dataset = $sth->fetchall_arrayref();
                   2240:     if (ref($dataset) eq 'ARRAY' && scalar(@$dataset)>0) {
                   2241:         return $dataset;
                   2242:     }
                   2243: 
1.100     matthew  2244: }
1.61      matthew  2245: 
                   2246: ################################################
                   2247: ################################################
                   2248: 
                   2249: =pod
                   2250: 
1.116     matthew  2251: =item &get_student_scores($Sections,$Symbs,$enrollment,$courseid)
1.113     matthew  2252: 
                   2253: =cut
                   2254: 
                   2255: ################################################
                   2256: ################################################
                   2257: sub get_student_scores {
1.121     matthew  2258:     my ($Sections,$Symbs,$enrollment,$courseid,$starttime,$endtime) = @_;
1.113     matthew  2259:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
                   2260:     &setup_table_names($courseid);
                   2261:     my $dbh = &Apache::lonmysql::get_dbh();
                   2262:     return (undef) if (! defined($dbh));
                   2263:     my $tmptable = $courseid.'_temp_'.time;
1.114     matthew  2264:     #
                   2265:     my $symb_requirements;
1.113     matthew  2266:     if (defined($Symbs)  && @$Symbs) {
                   2267:         $symb_requirements = '('.
1.114     matthew  2268:             join(' OR ', map{ "(a.symb_id='".&get_symb_id($_->{'symb'}).
1.121     matthew  2269:                               "' AND a.part_id='".&get_part_id($_->{'part'}).
                   2270:                               "')"
1.113     matthew  2271:                               } @$Symbs).')';
                   2272:     }
1.114     matthew  2273:     #
                   2274:     my $student_requirements;
                   2275:     if ( (defined($Sections) && $Sections->[0] ne 'all')) {
1.113     matthew  2276:         $student_requirements = '('.
1.114     matthew  2277:             join(' OR ', map { "b.section='".$_."'" } @$Sections
1.113     matthew  2278:                  ).')';
                   2279:     }
1.114     matthew  2280:     #
                   2281:     my $enrollment_requirements=undef;
                   2282:     if (defined($enrollment) && $enrollment ne 'Any') {
                   2283:         $enrollment_requirements = "b.status='".$enrollment."'";
                   2284:     }
1.121     matthew  2285:     #
                   2286:     my $time_requirements = undef;
                   2287:     if (defined($starttime)) {
                   2288:         $time_requirements .= "a.timestamp>='".$starttime."'";
                   2289:         if (defined($endtime)) {
                   2290:             $time_requirements .= " AND a.timestamp<='".$endtime."'";
                   2291:         }
                   2292:     } elsif (defined($endtime)) {
                   2293:         $time_requirements .= "a.timestamp<='".$endtime."'";
                   2294:     }
1.114     matthew  2295:     ##
                   2296:     ##
1.113     matthew  2297:     my $request = 'CREATE TEMPORARY TABLE IF NOT EXISTS '.$tmptable.
1.114     matthew  2298:         ' SELECT a.student_id,SUM(a.awarded) AS score FROM '.
                   2299:         $performance_table.' AS a ';
                   2300:     if (defined($student_requirements) || defined($enrollment_requirements)) {
                   2301:         $request .= ' NATURAL LEFT JOIN '.$student_table.' AS b ';
                   2302:     }
                   2303:     if (defined($symb_requirements)      || 
                   2304:         defined($student_requirements)   ||
                   2305:         defined($enrollment_requirements) ) {
1.113     matthew  2306:         $request .= ' WHERE ';
                   2307:     }
1.114     matthew  2308:     if (defined($symb_requirements)) {
                   2309:         $request .= $symb_requirements.' AND ';
                   2310:     }
                   2311:     if (defined($student_requirements)) {
                   2312:         $request .= $student_requirements.' AND ';
                   2313:     }
                   2314:     if (defined($enrollment_requirements)) {
                   2315:         $request .= $enrollment_requirements.' AND ';
                   2316:     }
1.121     matthew  2317:     if (defined($time_requirements)) {
                   2318:         $request .= $time_requirements.' AND ';
                   2319:     }
                   2320:     $request =~ s/ AND $//; # Strip of the trailing ' AND '.
1.114     matthew  2321:     $request .= ' GROUP BY a.student_id';
                   2322: #    &Apache::lonnet::logthis("request = \n".$request);
1.113     matthew  2323:     my $sth = $dbh->prepare($request);
                   2324:     $sth->execute();
                   2325:     if ($dbh->err) {
                   2326:         &Apache::lonnet::logthis('error = '.$dbh->errstr());
                   2327:         return undef;
                   2328:     }
                   2329:     $request = 'SELECT score,COUNT(*) FROM '.$tmptable.' GROUP BY score';
                   2330: #    &Apache::lonnet::logthis("request = \n".$request);
                   2331:     $sth = $dbh->prepare($request);
                   2332:     $sth->execute();
                   2333:     if ($dbh->err) {
                   2334:         &Apache::lonnet::logthis('error = '.$dbh->errstr());
                   2335:         return undef;
                   2336:     }
                   2337:     my $dataset = $sth->fetchall_arrayref();
                   2338:     return $dataset;
                   2339: }
                   2340: 
                   2341: ################################################
                   2342: ################################################
                   2343: 
                   2344: =pod
                   2345: 
1.61      matthew  2346: =item &setup_table_names()
                   2347: 
                   2348: input: course id
                   2349: 
                   2350: output: none
                   2351: 
                   2352: Cleans up the package variables for local caching.
                   2353: 
                   2354: =cut
                   2355: 
                   2356: ################################################
                   2357: ################################################
                   2358: sub setup_table_names {
                   2359:     my ($courseid) = @_;
                   2360:     if (! defined($courseid)) {
                   2361:         $courseid = $ENV{'request.course.id'};
                   2362:     }
                   2363:     #
                   2364:     if (! defined($current_course) || $current_course ne $courseid) {
                   2365:         # Clear out variables
                   2366:         $have_read_part_table = 0;
                   2367:         undef(%ids_by_part);
                   2368:         undef(%parts_by_id);
                   2369:         $have_read_symb_table = 0;
                   2370:         undef(%ids_by_symb);
                   2371:         undef(%symbs_by_id);
                   2372:         $have_read_student_table = 0;
                   2373:         undef(%ids_by_student);
                   2374:         undef(%students_by_id);
                   2375:         #
                   2376:         $current_course = $courseid;
                   2377:     }
                   2378:     #
                   2379:     # Set up database names
                   2380:     my $base_id = $courseid;
                   2381:     $symb_table        = $base_id.'_'.'symb';
                   2382:     $part_table        = $base_id.'_'.'part';
                   2383:     $student_table     = $base_id.'_'.'student';
                   2384:     $performance_table = $base_id.'_'.'performance';
                   2385:     $parameters_table  = $base_id.'_'.'parameters';
1.89      matthew  2386:     $fulldump_part_table      = $base_id.'_'.'partdata';
                   2387:     $fulldump_response_table  = $base_id.'_'.'responsedata';
                   2388:     $fulldump_timestamp_table = $base_id.'_'.'timestampdata';
                   2389:     #
                   2390:     @Tables = (
                   2391:                $symb_table,
                   2392:                $part_table,
                   2393:                $student_table,
                   2394:                $performance_table,
                   2395:                $parameters_table,
                   2396:                $fulldump_part_table,
                   2397:                $fulldump_response_table,
                   2398:                $fulldump_timestamp_table,
                   2399:                );
1.61      matthew  2400:     return;
1.3       stredwic 2401: }
1.1       stredwic 2402: 
1.35      matthew  2403: ################################################
                   2404: ################################################
                   2405: 
                   2406: =pod
                   2407: 
1.57      matthew  2408: =back
                   2409: 
                   2410: =item End of Local Data Caching Subroutines
                   2411: 
                   2412: =cut
                   2413: 
                   2414: ################################################
                   2415: ################################################
                   2416: 
1.89      matthew  2417: } # End scope of table identifiers
1.57      matthew  2418: 
                   2419: ################################################
                   2420: ################################################
                   2421: 
                   2422: =pod
                   2423: 
                   2424: =head3 Classlist Subroutines
                   2425: 
1.35      matthew  2426: =item &get_classlist();
                   2427: 
                   2428: Retrieve the classist of a given class or of the current class.  Student
                   2429: information is returned from the classlist.db file and, if needed,
                   2430: from the students environment.
                   2431: 
                   2432: Optional arguments are $cid, $cdom, and $cnum (course id, course domain,
                   2433: and course number, respectively).  Any omitted arguments will be taken 
                   2434: from the current environment ($ENV{'request.course.id'},
                   2435: $ENV{'course.'.$cid.'.domain'}, and $ENV{'course.'.$cid.'.num'}).
                   2436: 
                   2437: Returns a reference to a hash which contains:
                   2438:  keys    '$sname:$sdom'
1.111     raeburn  2439:  values  [$sdom,$sname,$end,$start,$id,$section,$fullname,$status,$type]
1.54      bowersj2 2440: 
                   2441: The constant values CL_SDOM, CL_SNAME, CL_END, etc. can be used
                   2442: as indices into the returned list to future-proof clients against
                   2443: changes in the list order.
1.35      matthew  2444: 
                   2445: =cut
                   2446: 
                   2447: ################################################
                   2448: ################################################
1.54      bowersj2 2449: 
                   2450: sub CL_SDOM     { return 0; }
                   2451: sub CL_SNAME    { return 1; }
                   2452: sub CL_END      { return 2; }
                   2453: sub CL_START    { return 3; }
                   2454: sub CL_ID       { return 4; }
                   2455: sub CL_SECTION  { return 5; }
                   2456: sub CL_FULLNAME { return 6; }
                   2457: sub CL_STATUS   { return 7; }
1.111     raeburn  2458: sub CL_TYPE     { return 8; }
1.35      matthew  2459: 
                   2460: sub get_classlist {
                   2461:     my ($cid,$cdom,$cnum) = @_;
                   2462:     $cid = $cid || $ENV{'request.course.id'};
                   2463:     $cdom = $cdom || $ENV{'course.'.$cid.'.domain'};
                   2464:     $cnum = $cnum || $ENV{'course.'.$cid.'.num'};
1.57      matthew  2465:     my $now = time;
1.35      matthew  2466:     #
                   2467:     my %classlist=&Apache::lonnet::dump('classlist',$cdom,$cnum);
                   2468:     while (my ($student,$info) = each(%classlist)) {
1.60      matthew  2469:         if ($student =~ /^(con_lost|error|no_such_host)/i) {
                   2470:             &Apache::lonnet::logthis('get_classlist error for '.$cid.':'.$student);
                   2471:             return undef;
                   2472:         }
1.35      matthew  2473:         my ($sname,$sdom) = split(/:/,$student);
                   2474:         my @Values = split(/:/,$info);
1.111     raeburn  2475:         my ($end,$start,$id,$section,$fullname,$type);
1.35      matthew  2476:         if (@Values > 2) {
1.111     raeburn  2477:             ($end,$start,$id,$section,$fullname,$type) = @Values;
1.35      matthew  2478:         } else { # We have to get the data ourselves
                   2479:             ($end,$start) = @Values;
1.37      matthew  2480:             $section = &Apache::lonnet::getsection($sdom,$sname,$cid);
1.35      matthew  2481:             my %info=&Apache::lonnet::get('environment',
                   2482:                                           ['firstname','middlename',
                   2483:                                            'lastname','generation','id'],
                   2484:                                           $sdom, $sname);
                   2485:             my ($tmp) = keys(%info);
                   2486:             if ($tmp =~/^(con_lost|error|no_such_host)/i) {
                   2487:                 $fullname = 'not available';
                   2488:                 $id = 'not available';
1.38      matthew  2489:                 &Apache::lonnet::logthis('unable to retrieve environment '.
                   2490:                                          'for '.$sname.':'.$sdom);
1.35      matthew  2491:             } else {
                   2492:                 $fullname = &ProcessFullName(@info{qw/lastname generation 
                   2493:                                                        firstname middlename/});
                   2494:                 $id = $info{'id'};
                   2495:             }
1.36      matthew  2496:             # Update the classlist with this students information
                   2497:             if ($fullname ne 'not available') {
                   2498:                 my $enrolldata = join(':',$end,$start,$id,$section,$fullname);
                   2499:                 my $reply=&Apache::lonnet::cput('classlist',
                   2500:                                                 {$student => $enrolldata},
                   2501:                                                 $cdom,$cnum);
                   2502:                 if ($reply !~ /^(ok|delayed)/) {
                   2503:                     &Apache::lonnet::logthis('Unable to update classlist for '.
                   2504:                                              'student '.$sname.':'.$sdom.
                   2505:                                              ' error:'.$reply);
                   2506:                 }
                   2507:             }
1.35      matthew  2508:         }
                   2509:         my $status='Expired';
                   2510:         if(((!$end) || $now < $end) && ((!$start) || ($now > $start))) {
                   2511:             $status='Active';
                   2512:         }
                   2513:         $classlist{$student} = 
1.111     raeburn  2514:             [$sdom,$sname,$end,$start,$id,$section,$fullname,$status,$type];
1.35      matthew  2515:     }
                   2516:     if (wantarray()) {
                   2517:         return (\%classlist,['domain','username','end','start','id',
1.111     raeburn  2518:                              'section','fullname','status','type']);
1.35      matthew  2519:     } else {
                   2520:         return \%classlist;
                   2521:     }
                   2522: }
                   2523: 
1.1       stredwic 2524: # ----- END HELPER FUNCTIONS --------------------------------------------
                   2525: 
                   2526: 1;
                   2527: __END__
1.36      matthew  2528: 
1.35      matthew  2529: 

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