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

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

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