Annotation of loncom/interface/loncoursedata.pm, revision 1.69

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

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