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

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

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