File:  [LON-CAPA] / loncom / interface / loncoursedata.pm
Revision 1.90: download - view: text, annotated - select for diffs
Fri Sep 26 19:23:14 2003 UTC (20 years, 9 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
In full updates we need to pick up and store the response specific parameters
'submissiongrading' and 'molecule'.

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

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