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

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

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