File:  [LON-CAPA] / loncom / interface / loncoursedata.pm
Revision 1.140: download - view: text, annotated - select for diffs
Thu Oct 7 22:12:47 2004 UTC (19 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- fixes bug#3350 hopefully for good.
    - $navmaps objects never actaully got cleaned up due the resource objects in it holding a reference back to the navmap object, this meant the hashes didn't get untied and that we leaked memory
    - needs WeakRef

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

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