File:  [LON-CAPA] / loncom / interface / loncoursedata.pm
Revision 1.96: download - view: text, annotated - select for diffs
Tue Sep 30 15:47:40 2003 UTC (20 years, 8 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Should be 'okay', not simply not begin with 'error'.

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

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