File:  [LON-CAPA] / loncom / interface / loncoursedata.pm
Revision 1.61: download - view: text, annotated - select for diffs
Tue Mar 25 22:29:31 2003 UTC (21 years, 2 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Removed &DownloadClasslist, &DownloadCourseInformation, &ProcessTopResourceMap,
&ProcessClasslist, &ProcessStudentData, &ExtractStudentData,
&CheckDateStampError, &TestCacheData, &DownloadStudentCourseData,
&DownloadStudentCourseDataSeparate, and &CheckForResidualDownload

Local Caching:
Added flags to &get_part_id, &get_symb_id, and &get_student_id to fix a bug
where they automatically added the part/symb/student to the table the first
time they were called instead of reading the table to get the value.
&get_current_state was reduced in size by moving its initialization code
to &setup_table_names.  &setup_table_names was relocated to the tail of the
local caching code.

Statistics:
Added &get_problem_statistics.  It does not currently limit the statistics
to a set of students, but will soon.  Classification of students is also
unimplemented.

Added SQL helper function &execute_SQL_request to encapsulate the
'prepare request, execute request, get returned row' sequence and make
debugging easier.

    1: # The LearningOnline Network with CAPA
    2: #
    3: # $Id: loncoursedata.pm,v 1.61 2003/03/25 22:29:31 matthew 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: AT THIS TIME THE USE OF THIS FUNCTION IS *NOT* RECOMMENDED
   77: 
   78: Use lonnavmaps to build a data structure describing the order and 
   79: assessment contents of each sequence in the current course.
   80: 
   81: The returned structure is a hash reference. 
   82: 
   83: { title => 'title',
   84:   symb  => 'symb',
   85:   src   => '/s/o/u/r/c/e',
   86:   type  => (container|assessment),
   87:   num_assess   => 2,               # only for container
   88:   parts        => [11,13,15],      # only for assessment
   89:   response_ids => [12,14,16],      # only for assessment
   90:   contents     => [........]       # only for container
   91: }
   92: 
   93: $hash->{'contents'} is a reference to an array of hashes of the same structure.
   94: 
   95: Also returned are array references to the sequences and assessments contained
   96: in the course.
   97: 
   98: 
   99: =cut
  100: 
  101: ####################################################
  102: ####################################################
  103: sub get_sequence_assessment_data {
  104:     my $fn=$ENV{'request.course.fn'};
  105:     ##
  106:     ## use navmaps
  107:     my $navmap = Apache::lonnavmaps::navmap->new(Apache->request,$fn.".db",
  108:                                                  $fn."_parms.db",1,0);
  109:     if (!defined($navmap)) {
  110:         return 'Can not open Coursemap';
  111:     }
  112:     my $iterator = $navmap->getIterator(undef, undef, undef, 1);
  113:     my $curRes = $iterator->next(); # Top level sequence
  114:     ##
  115:     ## Prime the pump 
  116:     ## 
  117:     ## We are going to loop until we run out of sequences/pages to explore for
  118:     ## resources.  This means we have to start out with something to look
  119:     ## at.
  120:     my $title = $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
  121:     my $symb  = 'top';
  122:     my $src   = 'not applicable';
  123:     #
  124:     my @Sequences; 
  125:     my @Assessments;
  126:     my @Nested_Sequences = ();   # Stack of sequences, keeps track of depth
  127:     my $top = { title    => $title,
  128:                 src      => $src,
  129:                 symb     => $symb,
  130:                 type     => 'container',
  131:                 num_assess => 0,
  132:                 num_assess_parts => 0,
  133:                 contents   => [], };
  134:     push (@Sequences,$top);
  135:     push (@Nested_Sequences, $top);
  136:     #
  137:     # We need to keep track of which sequences contain homework problems
  138:     # 
  139:     my $previous;
  140:     $curRes = $iterator->next(); # BEGIN_MAP
  141:     $curRes = $iterator->next(); # The first item in the top level map.
  142:     while (scalar(@Nested_Sequences)) {
  143:         $previous = $curRes;
  144:         $curRes = $iterator->next();
  145:         my $currentmap = $Nested_Sequences[-1]; # Last one on the stack
  146:         if ($curRes == $iterator->BEGIN_MAP()) {
  147:             # get the map itself, instead of BEGIN_MAP
  148:             $title = $previous->title();
  149:             $symb  = $previous->symb();
  150:             $src   = $previous->src();
  151:             my $newmap = { title    => $title,
  152:                            src      => $src,
  153:                            symb     => $symb,
  154:                            type     => 'container',
  155:                            num_assess => 0,
  156:                            contents   => [],
  157:                        };
  158:             push (@{$currentmap->{'contents'}},$newmap); # this is permanent
  159:             push (@Sequences,$newmap);
  160:             push (@Nested_Sequences, $newmap); # this is a stack
  161:             next;
  162:         }
  163:         if ($curRes == $iterator->END_MAP()) {
  164:             pop(@Nested_Sequences);
  165:             next;
  166:         }
  167:         next if (! ref($curRes));
  168:         next if (! $curRes->is_problem());# && !$curRes->randomout);
  169:         # Okay, from here on out we only deal with assessments
  170:         $title = $curRes->title();
  171:         $symb  = $curRes->symb();
  172:         $src   = $curRes->src();
  173:         my $parts = $curRes->parts();
  174:         my $assessment = { title => $title,
  175:                            src   => $src,
  176:                            symb  => $symb,
  177:                            type  => 'assessment',
  178:                            parts => $parts,
  179:                            num_parts => scalar(@$parts),
  180:                        };
  181:         push(@Assessments,$assessment);
  182:         push(@{$currentmap->{'contents'}},$assessment);
  183:         $currentmap->{'num_assess'}++;
  184:         $currentmap->{'num_assess_parts'}+= scalar(@$parts);
  185:     }
  186:     $navmap->untieHashes();
  187:     return ($top,\@Sequences,\@Assessments);
  188: }
  189: 
  190: sub LoadDiscussion {
  191:     my ($courseID)=@_;
  192:     my %Discuss=();
  193:     my %contrib=&Apache::lonnet::dump(
  194:                 $courseID,
  195:                 $ENV{'course.'.$courseID.'.domain'},
  196:                 $ENV{'course.'.$courseID.'.num'});
  197: 				 
  198:     #my %contrib=&DownloadCourseInformation($name, $courseID, 0);
  199: 
  200:     foreach my $temp(keys %contrib) {
  201: 	if ($temp=~/^version/) {
  202: 	    my $ver=$contrib{$temp};
  203: 	    my ($dummy,$prb)=split(':',$temp);
  204: 	    for (my $idx=1; $idx<=$ver; $idx++ ) {
  205: 		my $name=$contrib{"$idx:$prb:sendername"};
  206: 		$Discuss{"$name:$prb"}=$idx;	
  207: 	    }
  208: 	}
  209:     }       
  210: 
  211:     return \%Discuss;
  212: }
  213: 
  214: =pod
  215: 
  216: =item &ProcessFullName()
  217: 
  218: Takes lastname, generation, firstname, and middlename (or some partial
  219: set of this data) and returns the full name version as a string.  Format
  220: is Lastname generation, firstname middlename or a subset of this.
  221: 
  222: =cut
  223: 
  224: sub ProcessFullName {
  225:     my ($lastname, $generation, $firstname, $middlename)=@_;
  226:     my $Str = '';
  227: 
  228:     # Strip whitespace preceeding & following name components.
  229:     $lastname   =~ s/(\s+$|^\s+)//g;
  230:     $generation =~ s/(\s+$|^\s+)//g;
  231:     $firstname  =~ s/(\s+$|^\s+)//g;
  232:     $middlename =~ s/(\s+$|^\s+)//g;
  233: 
  234:     if($lastname ne '') {
  235: 	$Str .= $lastname;
  236: 	$Str .= ' '.$generation if ($generation ne '');
  237: 	$Str .= ',';
  238:         $Str .= ' '.$firstname  if ($firstname ne '');
  239:         $Str .= ' '.$middlename if ($middlename ne '');
  240:     } else {
  241:         $Str .= $firstname      if ($firstname ne '');
  242:         $Str .= ' '.$middlename if ($middlename ne '');
  243:         $Str .= ' '.$generation if ($generation ne '');
  244:     }
  245: 
  246:     return $Str;
  247: }
  248: 
  249: ################################################
  250: ################################################
  251: 
  252: =pod
  253: 
  254: =item &make_into_hash($values);
  255: 
  256: Returns a reference to a hash as described by $values.  $values is
  257: assumed to be the result of 
  258:     join(':',map {&Apache::lonnet::escape($_)} %orighash);
  259: 
  260: This is a helper function for get_current_state.
  261: 
  262: =cut
  263: 
  264: ################################################
  265: ################################################
  266: sub make_into_hash {
  267:     my $values = shift;
  268:     my %tmp = map { &Apache::lonnet::unescape($_); }
  269:                                            split(':',$values);
  270:     return \%tmp;
  271: }
  272: 
  273: 
  274: ################################################
  275: ################################################
  276: 
  277: =pod
  278: 
  279: =head1 LOCAL DATA CACHING SUBROUTINES
  280: 
  281: The local caching is done using MySQL.  There is no fall-back implementation
  282: if MySQL is not running.
  283: 
  284: The programmers interface is to call &get_current_state() or some other
  285: primary interface subroutine (described below).  The internals of this 
  286: storage system are documented here.
  287: 
  288: There are six tables used to store student performance data (the results of
  289: a dumpcurrent).  Each of these tables is created in MySQL with a name of
  290: $courseid_*****, where ***** is 'symb', 'part', or whatever is appropriate 
  291: for the table.  The tables and their purposes are described below.
  292: 
  293: Some notes before we get started.
  294: 
  295: Each table must have a PRIMARY KEY, which is a column or set of columns which
  296: will serve to uniquely identify a row of data.  NULL is not allowed!
  297: 
  298: INDEXes work best on integer data.
  299: 
  300: JOIN is used to combine data from many tables into one output.
  301: 
  302: lonmysql.pm is used for some of the interface, specifically the table creation
  303: calls.  The inserts are done in bulk by directly calling the database handler.
  304: The SELECT ... JOIN statement used to retrieve the data does not have an
  305: interface in lonmysql.pm and I shudder at the thought of writing one.
  306: 
  307: =head3 Table Descriptions
  308: 
  309: =over 4
  310: 
  311: =item $symb_table
  312: 
  313: The symb_table has two columns.  The first is a 'symb_id' and the second
  314: is the text name for the 'symb' (limited to 64k).  The 'symb_id' is generated
  315: automatically by MySQL so inserts should be done on this table with an
  316: empty first element.  This table has its PRIMARY KEY on the 'symb_id'.
  317: 
  318: =item $part_table
  319: 
  320: The part_table has two columns.  The first is a 'part_id' and the second
  321: is the text name for the 'part' (limited to 100 characters).  The 'part_id' is
  322: generated automatically by MySQL so inserts should be done on this table with
  323: an empty first element.  This table has its PRIMARY KEY on the 'part' (100
  324: characters) and a KEY on 'part_id'.
  325: 
  326: =item $student_table
  327: 
  328: The student_table has two columns.  The first is a 'student_id' and the second
  329: is the text description of the 'student' (typically username:domain) (less
  330: than 100 characters).  The 'student_id' is automatically generated by MySQL.
  331: The use of the name 'student_id' is loaded, I know, but this ID is used ONLY 
  332: internally to the MySQL database and is not the same as the students ID 
  333: (stored in the students environment).  This table has its PRIMARY KEY on the
  334: 'student' (100 characters).
  335: 
  336: =item $updatetime_table
  337: 
  338: The updatetime_table has two columns.  The first is 'student' (100 characters,
  339: typically username:domain).  The second is 'updatetime', which is an unsigned
  340: integer, NOT a MySQL date.  This table has its PRIMARY KEY on 'student' (100
  341: characters).
  342: 
  343: =item $performance_table
  344: 
  345: The performance_table has 9 columns.  The first three are 'symb_id', 
  346: 'student_id', and 'part_id'.  These comprise the PRIMARY KEY for this table
  347: and are directly related to the $symb_table, $student_table, and $part_table
  348: described above.  MySQL does better indexing on numeric items than text,
  349: so we use these three "index tables".  The remaining columns are
  350: 'solved', 'tries', 'awarded', 'award', 'awarddetail', and 'timestamp'.
  351: These are either the MySQL type TINYTEXT or various integers ('tries' and 
  352: 'timestamp').  This table has KEYs of 'student_id' and 'symb_id'.
  353: For use of this table, see the functions described below.
  354: 
  355: =item $parameters_table
  356: 
  357: The parameters_table holds the data that does not fit neatly into the
  358: performance_table.  The parameters table has four columns: 'symb_id',
  359: 'student_id', 'parameter', and 'value'.  'symb_id', 'student_id', and
  360: 'parameter' comprise the PRIMARY KEY for this table.  'parameter' is 
  361: limited to 255 characters.  'value' is limited to 64k characters.
  362: 
  363: =back
  364: 
  365: =head3 Important Subroutines
  366: 
  367: Here is a brief overview of the subroutines which are likely to be of 
  368: interest:
  369: 
  370: =over 4
  371: 
  372: =item &get_current_state(): programmers interface.
  373: 
  374: =item &init_dbs(): table creation
  375: 
  376: =item &update_student_data(): data storage calls
  377: 
  378: =item &get_student_data_from_performance_cache(): data retrieval
  379: 
  380: =back
  381: 
  382: =head3 Main Documentation
  383: 
  384: =over 4
  385: 
  386: =cut
  387: 
  388: ################################################
  389: ################################################
  390: 
  391: ################################################
  392: ################################################
  393: {
  394: 
  395: my $current_course ='';
  396: my $symb_table;
  397: my $part_table;
  398: my $student_table;
  399: my $updatetime_table;
  400: my $performance_table;
  401: my $parameters_table;
  402: 
  403: ################################################
  404: ################################################
  405: 
  406: =pod
  407: 
  408: =item &init_dbs()
  409: 
  410: Input: course id
  411: 
  412: Output: 0 on success, positive integer on error
  413: 
  414: This routine issues the calls to lonmysql to create the tables used to
  415: store student data.
  416: 
  417: =cut
  418: 
  419: ################################################
  420: ################################################
  421: sub init_dbs {
  422:     my $courseid = shift;
  423:     &setup_table_names($courseid);
  424:     #
  425:     # Note - changes to this table must be reflected in the code that 
  426:     # stores the data (calls &Apache::lonmysql::store_row with this table
  427:     # id
  428:     my $symb_table_def = {
  429:         id => $symb_table,
  430:         permanent => 'no',
  431:         columns => [{ name => 'symb_id',
  432:                       type => 'MEDIUMINT UNSIGNED',
  433:                       restrictions => 'NOT NULL',
  434:                       auto_inc     => 'yes', },
  435:                     { name => 'symb',
  436:                       type => 'MEDIUMTEXT',
  437:                       restrictions => 'NOT NULL'},
  438:                     ],
  439:         'PRIMARY KEY' => ['symb_id'],
  440:     };
  441:     #
  442:     my $part_table_def = {
  443:         id => $part_table,
  444:         permanent => 'no',
  445:         columns => [{ name => 'part_id',
  446:                       type => 'MEDIUMINT UNSIGNED',
  447:                       restrictions => 'NOT NULL',
  448:                       auto_inc     => 'yes', },
  449:                     { name => 'part',
  450:                       type => 'VARCHAR(100)',
  451:                       restrictions => 'NOT NULL'},
  452:                     ],
  453:         'PRIMARY KEY' => ['part (100)'],
  454:         'KEY' => [{ columns => ['part_id']},],
  455:     };
  456:     #
  457:     my $student_table_def = {
  458:         id => $student_table,
  459:         permanent => 'no',
  460:         columns => [{ name => 'student_id',
  461:                       type => 'MEDIUMINT UNSIGNED',
  462:                       restrictions => 'NOT NULL',
  463:                       auto_inc     => 'yes', },
  464:                     { name => 'student',
  465:                       type => 'VARCHAR(100)',
  466:                       restrictions => 'NOT NULL'},
  467:                     ],
  468:         'PRIMARY KEY' => ['student (100)'],
  469:         'KEY' => [{ columns => ['student_id']},],
  470:     };
  471:     #
  472:     my $updatetime_table_def = {
  473:         id => $updatetime_table,
  474:         permanent => 'no',
  475:         columns => [{ name => 'student',
  476:                       type => 'VARCHAR(100)',
  477:                       restrictions => 'NOT NULL UNIQUE',},
  478:                     { name => 'updatetime',
  479:                       type => 'INT UNSIGNED',
  480:                       restrictions => 'NOT NULL' },
  481:                     ],
  482:         'PRIMARY KEY' => ['student (100)'],
  483:     };
  484:     #
  485:     my $performance_table_def = {
  486:         id => $performance_table,
  487:         permanent => 'no',
  488:         columns => [{ name => 'symb_id',
  489:                       type => 'MEDIUMINT UNSIGNED',
  490:                       restrictions => 'NOT NULL'  },
  491:                     { name => 'student_id',
  492:                       type => 'MEDIUMINT UNSIGNED',
  493:                       restrictions => 'NOT NULL'  },
  494:                     { name => 'part_id',
  495:                       type => 'MEDIUMINT UNSIGNED',
  496:                       restrictions => 'NOT NULL' },
  497:                     { name => 'solved',
  498:                       type => 'TINYTEXT' },
  499:                     { name => 'tries',
  500:                       type => 'SMALLINT UNSIGNED' },
  501:                     { name => 'awarded',
  502:                       type => 'TINYTEXT' },
  503:                     { name => 'award',
  504:                       type => 'TINYTEXT' },
  505:                     { name => 'awarddetail',
  506:                       type => 'TINYTEXT' },
  507:                     { name => 'timestamp',
  508:                       type => 'INT UNSIGNED'},
  509:                     { name => 'weight',
  510:                       type => 'INT UNSIGNED'},
  511:                     ],
  512:         'PRIMARY KEY' => ['symb_id','student_id','part_id'],
  513:         'KEY' => [{ columns=>['student_id'] },
  514:                   { columns=>['symb_id'] },],
  515:     };
  516:     #
  517:     my $parameters_table_def = {
  518:         id => $parameters_table,
  519:         permanent => 'no',
  520:         columns => [{ name => 'symb_id',
  521:                       type => 'MEDIUMINT UNSIGNED',
  522:                       restrictions => 'NOT NULL'  },
  523:                     { name => 'student_id',
  524:                       type => 'MEDIUMINT UNSIGNED',
  525:                       restrictions => 'NOT NULL'  },
  526:                     { name => 'parameter',
  527:                       type => 'TINYTEXT',
  528:                       restrictions => 'NOT NULL'  },
  529:                     { name => 'value',
  530:                       type => 'MEDIUMTEXT' },
  531:                     ],
  532:         'PRIMARY KEY' => ['symb_id','student_id','parameter (255)'],
  533:     };
  534:     #
  535:     # Create the tables
  536:     my $tableid;
  537:     $tableid = &Apache::lonmysql::create_table($symb_table_def);
  538:     if (! defined($tableid)) {
  539:         &Apache::lonnet::logthis("error creating symb_table: ".
  540:                                  &Apache::lonmysql::get_error());
  541:         return 1;
  542:     }
  543:     #
  544:     $tableid = &Apache::lonmysql::create_table($part_table_def);
  545:     if (! defined($tableid)) {
  546:         &Apache::lonnet::logthis("error creating part_table: ".
  547:                                  &Apache::lonmysql::get_error());
  548:         return 2;
  549:     }
  550:     #
  551:     $tableid = &Apache::lonmysql::create_table($student_table_def);
  552:     if (! defined($tableid)) {
  553:         &Apache::lonnet::logthis("error creating student_table: ".
  554:                                  &Apache::lonmysql::get_error());
  555:         return 3;
  556:     }
  557:     #
  558:     $tableid = &Apache::lonmysql::create_table($updatetime_table_def);
  559:     if (! defined($tableid)) {
  560:         &Apache::lonnet::logthis("error creating updatetime_table: ".
  561:                                  &Apache::lonmysql::get_error());
  562:         return 4;
  563:     }
  564:     #
  565:     $tableid = &Apache::lonmysql::create_table($performance_table_def);
  566:     if (! defined($tableid)) {
  567:         &Apache::lonnet::logthis("error creating preformance_table: ".
  568:                                  &Apache::lonmysql::get_error());
  569:         return 5;
  570:     }
  571:     #
  572:     $tableid = &Apache::lonmysql::create_table($parameters_table_def);
  573:     if (! defined($tableid)) {
  574:         &Apache::lonnet::logthis("error creating parameters_table: ".
  575:                                  &Apache::lonmysql::get_error());
  576:         return 6;
  577:     }
  578:     return 0;
  579: }
  580: 
  581: ################################################
  582: ################################################
  583: 
  584: =pod
  585: 
  586: =item &get_part_id()
  587: 
  588: Get the MySQL id of a problem part string.
  589: 
  590: Input: $part
  591: 
  592: Output: undef on error, integer $part_id on success.
  593: 
  594: =item &get_part()
  595: 
  596: Get the string describing a part from the MySQL id of the problem part.
  597: 
  598: Input: $part_id
  599: 
  600: Output: undef on error, $part string on success.
  601: 
  602: =cut
  603: 
  604: ################################################
  605: ################################################
  606: 
  607: my $have_read_part_table = 0;
  608: my %ids_by_part;
  609: my %parts_by_id;
  610: 
  611: sub get_part_id {
  612:     my ($part) = @_;
  613:     $part = 0 if (! defined($part));
  614:     if (! $have_read_part_table) {
  615:         my @Result = &Apache::lonmysql::get_rows($part_table);
  616:         foreach (@Result) {
  617:             $ids_by_part{$_->[1]}=$_->[0];
  618:         }
  619:         $have_read_part_table = 1;
  620:     }
  621:     if (! exists($ids_by_part{$part})) {
  622:         &Apache::lonmysql::store_row($part_table,[undef,$part]);
  623:         undef(%ids_by_part);
  624:         my @Result = &Apache::lonmysql::get_rows($part_table);
  625:         foreach (@Result) {
  626:             $ids_by_part{$_->[1]}=$_->[0];
  627:         }
  628:     }
  629:     return $ids_by_part{$part} if (exists($ids_by_part{$part}));
  630:     return undef; # error
  631: }
  632: 
  633: sub get_part {
  634:     my ($part_id) = @_;
  635:     if (! exists($parts_by_id{$part_id})  || 
  636:         ! defined($parts_by_id{$part_id}) ||
  637:         $parts_by_id{$part_id} eq '') {
  638:         my @Result = &Apache::lonmysql::get_rows($part_table);
  639:         foreach (@Result) {
  640:             $parts_by_id{$_->[0]}=$_->[1];
  641:         }
  642:     }
  643:     return $parts_by_id{$part_id} if(exists($parts_by_id{$part_id}));
  644:     return undef; # error
  645: }
  646: 
  647: ################################################
  648: ################################################
  649: 
  650: =pod
  651: 
  652: =item &get_symb_id()
  653: 
  654: Get the MySQL id of a symb.
  655: 
  656: Input: $symb
  657: 
  658: Output: undef on error, integer $symb_id on success.
  659: 
  660: =item &get_symb()
  661: 
  662: Get the symb associated with a MySQL symb_id.
  663: 
  664: Input: $symb_id
  665: 
  666: Output: undef on error, $symb on success.
  667: 
  668: =cut
  669: 
  670: ################################################
  671: ################################################
  672: 
  673: my $have_read_symb_table = 0;
  674: my %ids_by_symb;
  675: my %symbs_by_id;
  676: 
  677: sub get_symb_id {
  678:     my ($symb) = @_;
  679:     if (! $have_read_symb_table) {
  680:         my @Result = &Apache::lonmysql::get_rows($symb_table);
  681:         foreach (@Result) {
  682:             $ids_by_symb{$_->[1]}=$_->[0];
  683:         }
  684:         $have_read_symb_table = 1;
  685:     }
  686:     if (! exists($ids_by_symb{$symb})) {
  687:         &Apache::lonmysql::store_row($symb_table,[undef,$symb]);
  688:         undef(%ids_by_symb);
  689:         my @Result = &Apache::lonmysql::get_rows($symb_table);
  690:         foreach (@Result) {
  691:             $ids_by_symb{$_->[1]}=$_->[0];
  692:         }
  693:     }
  694:     return $ids_by_symb{$symb} if(exists( $ids_by_symb{$symb}));
  695:     return undef; # error
  696: }
  697: 
  698: sub get_symb {
  699:     my ($symb_id) = @_;
  700:     if (! exists($symbs_by_id{$symb_id})  || 
  701:         ! defined($symbs_by_id{$symb_id}) ||
  702:         $symbs_by_id{$symb_id} eq '') {
  703:         my @Result = &Apache::lonmysql::get_rows($symb_table);
  704:         foreach (@Result) {
  705:             $symbs_by_id{$_->[0]}=$_->[1];
  706:         }
  707:     }
  708:     return $symbs_by_id{$symb_id} if(exists( $symbs_by_id{$symb_id}));
  709:     return undef; # error
  710: }
  711: 
  712: ################################################
  713: ################################################
  714: 
  715: =pod
  716: 
  717: =item &get_student_id()
  718: 
  719: Get the MySQL id of a student.
  720: 
  721: Input: $sname, $dom
  722: 
  723: Output: undef on error, integer $student_id on success.
  724: 
  725: =item &get_student()
  726: 
  727: Get student username:domain associated with the MySQL student_id.
  728: 
  729: Input: $student_id
  730: 
  731: Output: undef on error, string $student (username:domain) on success.
  732: 
  733: =cut
  734: 
  735: ################################################
  736: ################################################
  737: 
  738: my $have_read_student_table = 0;
  739: my %ids_by_student;
  740: my %students_by_id;
  741: 
  742: sub get_student_id {
  743:     my ($sname,$sdom) = @_;
  744:     my $student = $sname.':'.$sdom;
  745:     if (! $have_read_student_table) {
  746:         my @Result = &Apache::lonmysql::get_rows($student_table);
  747:         foreach (@Result) {
  748:             $ids_by_student{$_->[1]}=$_->[0];
  749:         }
  750:         $have_read_student_table = 1;
  751:     }
  752:     if (! exists($ids_by_student{$student})) {
  753:         &Apache::lonmysql::store_row($student_table,[undef,$student]);
  754:         undef(%ids_by_student);
  755:         my @Result = &Apache::lonmysql::get_rows($student_table);
  756:         foreach (@Result) {
  757:             $ids_by_student{$_->[1]}=$_->[0];
  758:         }
  759:     }
  760:     return $ids_by_student{$student} if(exists( $ids_by_student{$student}));
  761:     return undef; # error
  762: }
  763: 
  764: sub get_student {
  765:     my ($student_id) = @_;
  766:     if (! exists($students_by_id{$student_id})  || 
  767:         ! defined($students_by_id{$student_id}) ||
  768:         $students_by_id{$student_id} eq '') {
  769:         my @Result = &Apache::lonmysql::get_rows($student_table);
  770:         foreach (@Result) {
  771:             $students_by_id{$_->[0]}=$_->[1];
  772:         }
  773:     }
  774:     return $students_by_id{$student_id} if(exists($students_by_id{$student_id}));
  775:     return undef; # error
  776: }
  777: 
  778: ################################################
  779: ################################################
  780: 
  781: =pod
  782: 
  783: =item &update_student_data()
  784: 
  785: Input: $sname, $sdom, $courseid
  786: 
  787: Output: $returnstatus, \%student_data
  788: 
  789: $returnstatus is a string describing any errors that occured.  'okay' is the
  790: default.
  791: \%student_data is the data returned by a call to lonnet::currentdump.
  792: 
  793: This subroutine loads a students data using lonnet::currentdump and inserts
  794: it into the MySQL database.  The inserts are done on two tables, 
  795: $performance_table and $parameters_table.  $parameters_table holds the data 
  796: that is not included in $performance_table.  See the description of 
  797: $performance_table elsewhere in this file.  The INSERT calls are made
  798: directly by this subroutine, not through lonmysql because we do a 'bulk'
  799: insert which takes advantage of MySQLs non-SQL compliant INSERT command to 
  800: insert multiple rows at a time.  If anything has gone wrong during this
  801: process, $returnstatus is updated with a description of the error and
  802: \%student_data is returned.  
  803: 
  804: Notice we do not insert the data and immediately query it.  This means it
  805: is possible for there to be data returned this first time that is not 
  806: available the second time.  CYA.
  807: 
  808: =cut
  809: 
  810: ################################################
  811: ################################################
  812: sub update_student_data {
  813:     my ($sname,$sdom,$courseid) = @_;
  814:     #
  815:     # Set up database names
  816:     &setup_table_names($courseid);
  817:     #
  818:     my $student_id = &get_student_id($sname,$sdom);
  819:     my $student = $sname.':'.$sdom;
  820:     #
  821:     my $returnstatus = 'okay';
  822:     #
  823:     # Download students data
  824:     my $time_of_retrieval = time;
  825:     my @tmp = &Apache::lonnet::currentdump($courseid,$sdom,$sname);
  826:     if ((scalar(@tmp) > 0) && ($tmp[0] =~ /^error:/)) {
  827:         &Apache::lonnet::logthis('error getting data for '.
  828:                                  $sname.':'.$sdom.' in course '.$courseid.
  829:                                  ':'.$tmp[0]);
  830:         $returnstatus = 'error getting data';
  831:         return $returnstatus;
  832:     }
  833:     if (scalar(@tmp) < 1) {
  834:         return ('no data',undef);
  835:     }
  836:     my %student_data = @tmp;
  837:     #
  838:     # Remove all of the students data from the table
  839:     my $dbh = &Apache::lonmysql::get_dbh();
  840:     $dbh->do('DELETE FROM '.$performance_table.' WHERE student_id='.
  841:              $student_id);
  842:     $dbh->do('DELETE FROM '.$parameters_table.' WHERE student_id='.
  843:              $student_id);
  844:     #
  845:     # Store away the data
  846:     #
  847:     my $starttime = Time::HiRes::time;
  848:     my $elapsed = 0;
  849:     my $rows_stored;
  850:     my $store_parameters_command  = 'INSERT INTO '.$parameters_table.
  851:         ' VALUES '."\n";
  852:     my $num_parameters = 0;
  853:     my $store_performance_command = 'INSERT INTO '.$performance_table.
  854:         ' VALUES '."\n";
  855:     return 'error' if (! defined($dbh));
  856:     while (my ($current_symb,$param_hash) = each(%student_data)) {
  857:         #
  858:         # make sure the symb is set up properly
  859:         my $symb_id = &get_symb_id($current_symb);
  860:         #
  861:         # Load data into the tables
  862:         foreach my $parameter (keys(%$param_hash)) {
  863:             my $value = $param_hash->{$parameter};
  864:             my $newstring;
  865:             if ($parameter !~ /(timestamp|resource\.(.*)\.(solved|tries|awarded|award|awarddetail|previous|weight))/) {
  866:                 $newstring = "('".join("','",
  867:                                        $symb_id,$student_id,
  868:                                        $parameter,$value)."'),\n";
  869:                 $num_parameters ++;
  870:                 if ($newstring !~ /''/) {
  871:                     $store_parameters_command .= $newstring;
  872:                     $rows_stored++;
  873:                 }
  874:             }
  875:             next if ($parameter !~ /^resource\.(.*)\.solved$/);
  876:             #
  877:             my $part = $1;
  878:             my $part_id = &get_part_id($part);
  879:             next if (!defined($part_id));
  880:             my $solved  = $value;
  881:             my $tries   = $param_hash->{'resource.'.$part.'.tries'};
  882:             my $awarded = $param_hash->{'resource.'.$part.'.awarded'};
  883:             my $award   = $param_hash->{'resource.'.$part.'.award'};
  884:             my $awarddetail = $param_hash->{'resource.'.$part.'.awarddetail'};
  885:             my $timestamp = $param_hash->{'timestamp'};
  886:             # use EXT to get the weight
  887:             my $weight  = &Apache::lonnet::EXT('resource.'.$part.'.weight',
  888:                                                $current_symb,$sdom,$sname);
  889:             # Give the weight back to the user
  890:             $param_hash->{'resource.'.$part.'.weight'}=$weight;
  891:             #
  892:             $solved      = '' if (! defined($awarded));
  893:             $tries       = '' if (! defined($tries));
  894:             $awarded     = '' if (! defined($awarded));
  895:             $award       = '' if (! defined($award));
  896:             $awarddetail = '' if (! defined($awarddetail));
  897:             $newstring = "('".join("','",$symb_id,$student_id,$part_id,
  898:                                    $solved,$tries,$awarded,$award,
  899:                                    $awarddetail,$timestamp,$weight)."'),\n";
  900:             $store_performance_command .= $newstring;
  901:             $rows_stored++;
  902:         }
  903:     }
  904:     chop $store_parameters_command;
  905:     chop $store_parameters_command;
  906:     chop $store_performance_command;
  907:     chop $store_performance_command;
  908:     my $start = Time::HiRes::time;
  909:     $dbh->do($store_parameters_command) if ($num_parameters>0);
  910:     if ($dbh->err()) {
  911:         &Apache::lonnet::logthis(' bigass insert error:'.$dbh->errstr());
  912:         &Apache::lonnet::logthis('command = '.$store_parameters_command);
  913:         $returnstatus = 'error: unable to insert parameters into database';
  914:         return $returnstatus,\%student_data;
  915:     }
  916:     $dbh->do($store_performance_command);
  917:     if ($dbh->err()) {
  918:         &Apache::lonnet::logthis(' bigass insert error:'.$dbh->errstr());
  919:         &Apache::lonnet::logthis('command = '.$store_performance_command);
  920:         $returnstatus = 'error: unable to insert performance into database';
  921:         return $returnstatus,\%student_data;
  922:     }
  923:     $elapsed += Time::HiRes::time - $start;
  924:     #
  925:     # Set the students update time
  926:     &Apache::lonmysql::replace_row($updatetime_table,
  927:                                    [$student,$time_of_retrieval]);
  928:     return ($returnstatus,\%student_data);
  929: }
  930: 
  931: ################################################
  932: ################################################
  933: 
  934: =pod
  935: 
  936: =item &ensure_current_data()
  937: 
  938: Input: $sname, $sdom, $courseid
  939: 
  940: Output: $status, $data
  941: 
  942: This routine ensures the data for a given student is up to date.  It calls
  943: &init_dbs() if the tables do not exist.  The $updatetime_table is queried
  944: to determine the time of the last update.  If the students data is out of
  945: date, &update_student_data() is called.  The return values from the call
  946: to &update_student_data() are returned.
  947: 
  948: =cut
  949: 
  950: ################################################
  951: ################################################
  952: sub ensure_current_data {
  953:     my ($sname,$sdom,$courseid) = @_;
  954:     my $status = 'okay';   # return value
  955:     #
  956:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
  957:     # 
  958:     # Clean out package variables
  959:     &setup_table_names($courseid);
  960:     #
  961:     # if the tables do not exist, make them
  962:     my @CurrentTable = &Apache::lonmysql::tables_in_db();
  963:     my ($found_symb,$found_student,$found_part,$found_update,
  964:         $found_performance,$found_parameters);
  965:     foreach (@CurrentTable) {
  966:         $found_symb        = 1 if ($_ eq $symb_table);
  967:         $found_student     = 1 if ($_ eq $student_table);
  968:         $found_part        = 1 if ($_ eq $part_table);
  969:         $found_update      = 1 if ($_ eq $updatetime_table);
  970:         $found_performance = 1 if ($_ eq $performance_table);
  971:         $found_parameters  = 1 if ($_ eq $parameters_table);
  972:     }
  973:     if (!$found_symb        || !$found_update || 
  974:         !$found_student     || !$found_part   ||
  975:         !$found_performance || !$found_parameters) {
  976:         if (&init_dbs($courseid)) {
  977:             return 'error';
  978:         }
  979:     }
  980:     #
  981:     # Get the update time for the user
  982:     my $updatetime = 0;
  983:     my $modifiedtime = &Apache::lonnet::GetFileTimestamp
  984:         ($sdom,$sname,$courseid.'.db',
  985:          $Apache::lonnet::perlvar{'lonUsersDir'});
  986:     #
  987:     my $student = $sname.':'.$sdom;
  988:     my @Result = &Apache::lonmysql::get_rows($updatetime_table,
  989:                                              "student ='$student'");
  990:     my $data = undef;
  991:     if (@Result) {
  992:         $updatetime = $Result[0]->[1];
  993:     }
  994:     if ($modifiedtime > $updatetime) {
  995:         ($status,$data) = &update_student_data($sname,$sdom,$courseid);
  996:     }
  997:     return ($status,$data);
  998: }
  999: 
 1000: ################################################
 1001: ################################################
 1002: 
 1003: =pod
 1004: 
 1005: =item &get_student_data_from_performance_cache()
 1006: 
 1007: Input: $sname, $sdom, $symb, $courseid
 1008: 
 1009: Output: hash reference containing the data for the given student.
 1010: If $symb is undef, all the students data is returned.
 1011: 
 1012: This routine is the heart of the local caching system.  See the description
 1013: of $performance_table, $symb_table, $student_table, and $part_table.  The
 1014: main task is building the MySQL request.  The tables appear in the request
 1015: in the order in which they should be parsed by MySQL.  When searching
 1016: on a student the $student_table is used to locate the 'student_id'.  All
 1017: rows in $performance_table which have a matching 'student_id' are returned,
 1018: with data from $part_table and $symb_table which match the entries in
 1019: $performance_table, 'part_id' and 'symb_id'.  When searching on a symb,
 1020: the $symb_table is processed first, with matching rows grabbed from 
 1021: $performance_table and filled in from $part_table and $student_table in
 1022: that order.  
 1023: 
 1024: Running 'EXPLAIN ' on the 'SELECT' statements generated can be quite 
 1025: interesting, especially if you play with the order the tables are listed.  
 1026: 
 1027: =cut
 1028: 
 1029: ################################################
 1030: ################################################
 1031: sub get_student_data_from_performance_cache {
 1032:     my ($sname,$sdom,$symb,$courseid)=@_;
 1033:     my $student = $sname.':'.$sdom if (defined($sname) && defined($sdom));
 1034:     &setup_table_names($courseid);
 1035:     #
 1036:     # Return hash
 1037:     my $studentdata;
 1038:     #
 1039:     my $dbh = &Apache::lonmysql::get_dbh();
 1040:     my $request = "SELECT ".
 1041:         "d.symb,c.part,a.solved,a.tries,a.awarded,a.award,a.awarddetail,".
 1042:             "a.timestamp,a.weight ";
 1043:     if (defined($student)) {
 1044:         $request .= "FROM $student_table AS b ".
 1045:             "LEFT JOIN $performance_table AS a ON b.student_id=a.student_id ".
 1046:             "LEFT JOIN $part_table AS c ON c.part_id = a.part_id ".
 1047:             "LEFT JOIN $symb_table AS d ON d.symb_id = a.symb_id ".
 1048:                 "WHERE student='$student'";
 1049:         if (defined($symb) && $symb ne '') {
 1050:             $request .= " AND d.symb='".$dbh->quote($symb)."'";
 1051:         }
 1052:     } elsif (defined($symb) && $symb ne '') {
 1053:         $request .= "FROM $symb_table as d ".
 1054:             "LEFT JOIN $performance_table AS a ON d.symb_id=a.symb_id ".
 1055:             "LEFT JOIN $part_table    AS c ON c.part_id = a.part_id ".
 1056:             "LEFT JOIN $student_table AS b ON b.student_id = a.student_id ".
 1057:                 "WHERE symb='".$dbh->quote($symb)."'";
 1058:     }
 1059:     my $starttime = Time::HiRes::time;
 1060:     my $rows_retrieved = 0;
 1061:     my $sth = $dbh->prepare($request);
 1062:     $sth->execute();
 1063:     if ($sth->err()) {
 1064:         &Apache::lonnet::logthis("Unable to execute MySQL request:");
 1065:         &Apache::lonnet::logthis("\n".$request."\n");
 1066:         &Apache::lonnet::logthis("error is:".$sth->errstr());
 1067:         return undef;
 1068:     }
 1069:     foreach my $row (@{$sth->fetchall_arrayref}) {
 1070:         $rows_retrieved++;
 1071:         my ($symb,$part,$solved,$tries,$awarded,$award,$awarddetail,$time,$weight) = 
 1072:             (@$row);
 1073:         my $base = 'resource.'.$part;
 1074:         $studentdata->{$symb}->{$base.'.solved'}  = $solved;
 1075:         $studentdata->{$symb}->{$base.'.tries'}   = $tries;
 1076:         $studentdata->{$symb}->{$base.'.awarded'} = $awarded;
 1077:         $studentdata->{$symb}->{$base.'.award'}   = $award;
 1078:         $studentdata->{$symb}->{$base.'.awarddetail'} = $awarddetail;
 1079:         $studentdata->{$symb}->{'timestamp'} = $time if (defined($time) && $time ne '');
 1080:         $studentdata->{$symb}->{'resource.'.$part.'.weight'}=$weight;
 1081:     }
 1082:     return $studentdata;
 1083: }
 1084: 
 1085: ################################################
 1086: ################################################
 1087: 
 1088: =pod
 1089: 
 1090: =item &get_current_state()
 1091: 
 1092: Input: $sname,$sdom,$symb,$courseid
 1093: 
 1094: Output: Described below
 1095: 
 1096: Retrieve the current status of a students performance.  $sname and
 1097: $sdom are the only required parameters.  If $symb is undef the results
 1098: of an &Apache::lonnet::currentdump() will be returned.  
 1099: If $courseid is undef it will be retrieved from the environment.
 1100: 
 1101: The return structure is based on &Apache::lonnet::currentdump.  If
 1102: $symb is unspecified, all the students data is returned in a hash of
 1103: the form:
 1104: ( 
 1105:   symb1 => { param1 => value1, param2 => value2 ... },
 1106:   symb2 => { param1 => value1, param2 => value2 ... },
 1107: )
 1108: 
 1109: If $symb is specified, a hash of 
 1110: (
 1111:   param1 => value1, 
 1112:   param2 => value2,
 1113: )
 1114: is returned.
 1115: 
 1116: If no data is found for $symb, or if the student has no performance data,
 1117: an empty list is returned.
 1118: 
 1119: =cut
 1120: 
 1121: ################################################
 1122: ################################################
 1123: sub get_current_state {
 1124:     my ($sname,$sdom,$symb,$courseid,$forcedownload)=@_;
 1125:     #
 1126:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
 1127:     #
 1128:     return () if (! defined($sname) || ! defined($sdom));
 1129:     #
 1130:     my ($status,$data) = &ensure_current_data($sname,$sdom,$courseid);
 1131:     #
 1132:     if (defined($data)) {
 1133:         return %$data;
 1134:     } elsif ($status eq 'no data') {
 1135:         return ();
 1136:     } else {
 1137:         if ($status ne 'okay' && $status ne '') {
 1138:             &Apache::lonnet::logthis('status = '.$status);
 1139:             return ();
 1140:         }
 1141:         my $returnhash = &get_student_data_from_performance_cache($sname,$sdom,
 1142:                                                       $symb,$courseid);
 1143:         return %$returnhash if (defined($returnhash));
 1144:     }
 1145:     return ();
 1146: }
 1147: 
 1148: ################################################
 1149: ################################################
 1150: 
 1151: =pod
 1152: 
 1153: =item &get_problem_statistics()
 1154: 
 1155: Gather data on a given problem.  The database is assumed to be 
 1156: populated and all local caching variables are assumed to be set
 1157: properly.  This means you need to call &ensure_current_data for
 1158: the students you are concerned with prior to calling this routine.
 1159: 
 1160: Inputs: $students, $symb, $part, $courseid
 1161: 
 1162: =cut
 1163: 
 1164: ################################################
 1165: ################################################
 1166: sub get_problem_statistics {
 1167:     my ($students,$symb,$part,$courseid) = @_;
 1168:     return if (! defined($symb) || ! defined($part));
 1169:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
 1170:     #
 1171:     my $symb_id = &get_symb_id($symb);
 1172:     my $part_id = &get_part_id($part);
 1173:     my $stats_table = $courseid.'_problem_stats';
 1174:     #
 1175:     &Apache::lonnet::logthis('symb id = '.$symb_id);
 1176:     &Apache::lonnet::logthis('part id = '.$part_id);
 1177: 
 1178:     my $dbh = &Apache::lonmysql::get_dbh();
 1179:     return undef if (! defined($dbh));
 1180:     &Apache::lonnet::logthis('dbh is defined');
 1181:     #
 1182:     # A) Number of Students attempting problem
 1183:     # B) Total number of tries of students attempting problem
 1184:     # C) Mod (largest number of tries for solving the problem)
 1185:     # D) Mean (average number of tries for solving the problem)
 1186:     # E) Number of students to solve the problem
 1187:     # F) Number of students to solve the problem by override
 1188:     # G) Number of students unable to solve the problem
 1189:     # H) Degree of difficulty : 1-(E+F)/B
 1190:     # I) Standard deviation of number of tries
 1191:     # J) Skew of tries: sqrt(sum(Xi-D)^3)/A
 1192:     #
 1193:     $dbh->do('DROP TABLE '.$stats_table);  # May return an error
 1194:     my $request = 
 1195:         'CREATE TEMPORARY TABLE '.$stats_table.
 1196:             ' SELECT student_id,solved,award,tries FROM '.$performance_table.
 1197:                 ' WHERE symb_id='.$symb_id.' AND part_id='.$part_id;
 1198: #    &Apache::lonnet::logthis($request);
 1199:     $dbh->do($request);
 1200:     my ($num,$tries,$mod,$mean,$STD) = &execute_SQL_request
 1201:         ($dbh,
 1202:          'SELECT COUNT(*),SUM(tries),MAX(tries),AVG(tries),STD(tries) FROM '.
 1203:          $stats_table);
 1204:     my ($Solved) = &execute_SQL_request($dbh,'SELECT COUNT(tries) FROM '.
 1205:                                         $stats_table.
 1206:                                         " WHERE solved='correct_by_student'");
 1207:     my ($solved) = &execute_SQL_request($dbh,'SELECT COUNT(tries) FROM '.
 1208:                                         $stats_table.
 1209:                                         " WHERE solved='correct_by_override'");
 1210:     $num    = 0 if (! defined($num));
 1211:     $tries  = 0 if (! defined($tries));
 1212:     $mod    = 0 if (! defined($mod));
 1213:     $STD    = 0 if (! defined($STD));
 1214:     $Solved = 0 if (! defined($Solved));
 1215:     $solved = 0 if (! defined($solved));
 1216:     #
 1217:     my $DegOfDiff = 'nan';
 1218:     $DegOfDiff = 1-($Solved + $solved)/$tries if ($tries>0);
 1219: 
 1220:     my $SKEW = 'nan';
 1221:     if ($num > 0) {
 1222:         ($SKEW) = &execute_SQL_request($dbh,'SELECT SQRT(SUM('.
 1223:                                      'POWER(tries - '.$STD.',3)'.
 1224:                                      '))/'.$num.' FROM '.$stats_table);
 1225:     }
 1226:     #
 1227:     $dbh->do('DROP TABLE '.$stats_table);  # May return an error
 1228:     return ($num,$tries,$mod,$mean,$Solved,$solved,$DegOfDiff,$STD,$SKEW);
 1229: }
 1230: 
 1231: sub execute_SQL_request {
 1232:     my ($dbh,$request)=@_;
 1233: #    &Apache::lonnet::logthis($request);
 1234:     my $sth = $dbh->prepare($request);
 1235:     $sth->execute();
 1236:     my $row = $sth->fetchrow_arrayref();
 1237:     if (ref($row) eq 'ARRAY' && scalar(@$row)>0) {
 1238:         return @$row;
 1239:     }
 1240:     return ();
 1241: }
 1242: 
 1243: 
 1244: ################################################
 1245: ################################################
 1246: 
 1247: =pod
 1248: 
 1249: =item &setup_table_names()
 1250: 
 1251: input: course id
 1252: 
 1253: output: none
 1254: 
 1255: Cleans up the package variables for local caching.
 1256: 
 1257: =cut
 1258: 
 1259: ################################################
 1260: ################################################
 1261: sub setup_table_names {
 1262:     my ($courseid) = @_;
 1263:     if (! defined($courseid)) {
 1264:         $courseid = $ENV{'request.course.id'};
 1265:     }
 1266:     #
 1267:     if (! defined($current_course) || $current_course ne $courseid) {
 1268:         # Clear out variables
 1269:         $have_read_part_table = 0;
 1270:         undef(%ids_by_part);
 1271:         undef(%parts_by_id);
 1272:         $have_read_symb_table = 0;
 1273:         undef(%ids_by_symb);
 1274:         undef(%symbs_by_id);
 1275:         $have_read_student_table = 0;
 1276:         undef(%ids_by_student);
 1277:         undef(%students_by_id);
 1278:         #
 1279:         $current_course = $courseid;
 1280:     }
 1281:     #
 1282:     # Set up database names
 1283:     my $base_id = $courseid;
 1284:     $symb_table        = $base_id.'_'.'symb';
 1285:     $part_table        = $base_id.'_'.'part';
 1286:     $student_table     = $base_id.'_'.'student';
 1287:     $updatetime_table  = $base_id.'_'.'updatetime';
 1288:     $performance_table = $base_id.'_'.'performance';
 1289:     $parameters_table  = $base_id.'_'.'parameters';
 1290:     return;
 1291: }
 1292: 
 1293: ################################################
 1294: ################################################
 1295: 
 1296: =pod
 1297: 
 1298: =back
 1299: 
 1300: =item End of Local Data Caching Subroutines
 1301: 
 1302: =cut
 1303: 
 1304: ################################################
 1305: ################################################
 1306: 
 1307: 
 1308: }
 1309: ################################################
 1310: ################################################
 1311: 
 1312: =pod
 1313: 
 1314: =head3 Classlist Subroutines
 1315: 
 1316: =item &get_classlist();
 1317: 
 1318: Retrieve the classist of a given class or of the current class.  Student
 1319: information is returned from the classlist.db file and, if needed,
 1320: from the students environment.
 1321: 
 1322: Optional arguments are $cid, $cdom, and $cnum (course id, course domain,
 1323: and course number, respectively).  Any omitted arguments will be taken 
 1324: from the current environment ($ENV{'request.course.id'},
 1325: $ENV{'course.'.$cid.'.domain'}, and $ENV{'course.'.$cid.'.num'}).
 1326: 
 1327: Returns a reference to a hash which contains:
 1328:  keys    '$sname:$sdom'
 1329:  values  [$sdom,$sname,$end,$start,$id,$section,$fullname,$status]
 1330: 
 1331: The constant values CL_SDOM, CL_SNAME, CL_END, etc. can be used
 1332: as indices into the returned list to future-proof clients against
 1333: changes in the list order.
 1334: 
 1335: =cut
 1336: 
 1337: ################################################
 1338: ################################################
 1339: 
 1340: sub CL_SDOM     { return 0; }
 1341: sub CL_SNAME    { return 1; }
 1342: sub CL_END      { return 2; }
 1343: sub CL_START    { return 3; }
 1344: sub CL_ID       { return 4; }
 1345: sub CL_SECTION  { return 5; }
 1346: sub CL_FULLNAME { return 6; }
 1347: sub CL_STATUS   { return 7; }
 1348: 
 1349: sub get_classlist {
 1350:     my ($cid,$cdom,$cnum) = @_;
 1351:     $cid = $cid || $ENV{'request.course.id'};
 1352:     $cdom = $cdom || $ENV{'course.'.$cid.'.domain'};
 1353:     $cnum = $cnum || $ENV{'course.'.$cid.'.num'};
 1354:     my $now = time;
 1355:     #
 1356:     my %classlist=&Apache::lonnet::dump('classlist',$cdom,$cnum);
 1357:     while (my ($student,$info) = each(%classlist)) {
 1358:         if ($student =~ /^(con_lost|error|no_such_host)/i) {
 1359:             &Apache::lonnet::logthis('get_classlist error for '.$cid.':'.$student);
 1360:             return undef;
 1361:         }
 1362:         my ($sname,$sdom) = split(/:/,$student);
 1363:         my @Values = split(/:/,$info);
 1364:         my ($end,$start,$id,$section,$fullname);
 1365:         if (@Values > 2) {
 1366:             ($end,$start,$id,$section,$fullname) = @Values;
 1367:         } else { # We have to get the data ourselves
 1368:             ($end,$start) = @Values;
 1369:             $section = &Apache::lonnet::getsection($sdom,$sname,$cid);
 1370:             my %info=&Apache::lonnet::get('environment',
 1371:                                           ['firstname','middlename',
 1372:                                            'lastname','generation','id'],
 1373:                                           $sdom, $sname);
 1374:             my ($tmp) = keys(%info);
 1375:             if ($tmp =~/^(con_lost|error|no_such_host)/i) {
 1376:                 $fullname = 'not available';
 1377:                 $id = 'not available';
 1378:                 &Apache::lonnet::logthis('unable to retrieve environment '.
 1379:                                          'for '.$sname.':'.$sdom);
 1380:             } else {
 1381:                 $fullname = &ProcessFullName(@info{qw/lastname generation 
 1382:                                                        firstname middlename/});
 1383:                 $id = $info{'id'};
 1384:             }
 1385:             # Update the classlist with this students information
 1386:             if ($fullname ne 'not available') {
 1387:                 my $enrolldata = join(':',$end,$start,$id,$section,$fullname);
 1388:                 my $reply=&Apache::lonnet::cput('classlist',
 1389:                                                 {$student => $enrolldata},
 1390:                                                 $cdom,$cnum);
 1391:                 if ($reply !~ /^(ok|delayed)/) {
 1392:                     &Apache::lonnet::logthis('Unable to update classlist for '.
 1393:                                              'student '.$sname.':'.$sdom.
 1394:                                              ' error:'.$reply);
 1395:                 }
 1396:             }
 1397:         }
 1398:         my $status='Expired';
 1399:         if(((!$end) || $now < $end) && ((!$start) || ($now > $start))) {
 1400:             $status='Active';
 1401:         }
 1402:         $classlist{$student} = 
 1403:             [$sdom,$sname,$end,$start,$id,$section,$fullname,$status];
 1404:     }
 1405:     if (wantarray()) {
 1406:         return (\%classlist,['domain','username','end','start','id',
 1407:                              'section','fullname','status']);
 1408:     } else {
 1409:         return \%classlist;
 1410:     }
 1411: }
 1412: 
 1413: # ----- END HELPER FUNCTIONS --------------------------------------------
 1414: 
 1415: 1;
 1416: __END__
 1417: 
 1418: 

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