File:  [LON-CAPA] / loncom / interface / loncoursedata.pm
Revision 1.72: download - view: text, annotated - select for diffs
Tue May 27 15:48:12 2003 UTC (21 years ago) by matthew
Branches: MAIN
CVS tags: version_0_99_1, HEAD
Debugging info to help track down white screen of death from spreadsheet.

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

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