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

1.1       stredwic    1: # The LearningOnline Network with CAPA
                      2: #
1.74    ! matthew     3: # $Id: loncoursedata.pm,v 1.73 2003/06/02 16:57:41 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: 
1.71      matthew   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: 
1.1       stredwic  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: 
1.71      matthew   255: ################################################
                    256: ################################################
1.1       stredwic  257: sub ProcessFullName {
                    258:     my ($lastname, $generation, $firstname, $middlename)=@_;
                    259:     my $Str = '';
                    260: 
1.34      matthew   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: 
1.1       stredwic  267:     if($lastname ne '') {
1.34      matthew   268: 	$Str .= $lastname;
                    269: 	$Str .= ' '.$generation if ($generation ne '');
                    270: 	$Str .= ',';
                    271:         $Str .= ' '.$firstname  if ($firstname ne '');
                    272:         $Str .= ' '.$middlename if ($middlename ne '');
1.1       stredwic  273:     } else {
1.34      matthew   274:         $Str .= $firstname      if ($firstname ne '');
                    275:         $Str .= ' '.$middlename if ($middlename ne '');
                    276:         $Str .= ' '.$generation if ($generation ne '');
1.1       stredwic  277:     }
                    278: 
                    279:     return $Str;
                    280: }
                    281: 
1.46      matthew   282: ################################################
                    283: ################################################
                    284: 
                    285: =pod
                    286: 
1.47      matthew   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 
1.57      matthew   291:     join(':',map {&Apache::lonnet::escape($_)} %orighash);
1.47      matthew   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: 
1.57      matthew   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:     #
1.73      matthew   458:     # Drop any of the existing tables
                    459:     foreach my $table ($symb_table,$part_table,$student_table,
                    460:                        $updatetime_table,$performance_table,
                    461:                        $parameters_table) {
                    462:         &Apache::lonmysql::drop_table($table);
                    463:     }
                    464:     #
1.57      matthew   465:     # Note - changes to this table must be reflected in the code that 
                    466:     # stores the data (calls &Apache::lonmysql::store_row with this table
                    467:     # id
                    468:     my $symb_table_def = {
                    469:         id => $symb_table,
                    470:         permanent => 'no',
                    471:         columns => [{ name => 'symb_id',
                    472:                       type => 'MEDIUMINT UNSIGNED',
                    473:                       restrictions => 'NOT NULL',
                    474:                       auto_inc     => 'yes', },
                    475:                     { name => 'symb',
                    476:                       type => 'MEDIUMTEXT',
                    477:                       restrictions => 'NOT NULL'},
                    478:                     ],
                    479:         'PRIMARY KEY' => ['symb_id'],
                    480:     };
                    481:     #
                    482:     my $part_table_def = {
                    483:         id => $part_table,
                    484:         permanent => 'no',
                    485:         columns => [{ name => 'part_id',
                    486:                       type => 'MEDIUMINT UNSIGNED',
                    487:                       restrictions => 'NOT NULL',
                    488:                       auto_inc     => 'yes', },
                    489:                     { name => 'part',
                    490:                       type => 'VARCHAR(100)',
                    491:                       restrictions => 'NOT NULL'},
                    492:                     ],
                    493:         'PRIMARY KEY' => ['part (100)'],
                    494:         'KEY' => [{ columns => ['part_id']},],
                    495:     };
                    496:     #
                    497:     my $student_table_def = {
                    498:         id => $student_table,
                    499:         permanent => 'no',
                    500:         columns => [{ name => 'student_id',
                    501:                       type => 'MEDIUMINT UNSIGNED',
                    502:                       restrictions => 'NOT NULL',
                    503:                       auto_inc     => 'yes', },
                    504:                     { name => 'student',
                    505:                       type => 'VARCHAR(100)',
                    506:                       restrictions => 'NOT NULL'},
                    507:                     ],
                    508:         'PRIMARY KEY' => ['student (100)'],
                    509:         'KEY' => [{ columns => ['student_id']},],
                    510:     };
                    511:     #
                    512:     my $updatetime_table_def = {
                    513:         id => $updatetime_table,
                    514:         permanent => 'no',
                    515:         columns => [{ name => 'student',
                    516:                       type => 'VARCHAR(100)',
                    517:                       restrictions => 'NOT NULL UNIQUE',},
                    518:                     { name => 'updatetime',
                    519:                       type => 'INT UNSIGNED',
                    520:                       restrictions => 'NOT NULL' },
                    521:                     ],
                    522:         'PRIMARY KEY' => ['student (100)'],
                    523:     };
                    524:     #
                    525:     my $performance_table_def = {
                    526:         id => $performance_table,
                    527:         permanent => 'no',
                    528:         columns => [{ name => 'symb_id',
                    529:                       type => 'MEDIUMINT UNSIGNED',
                    530:                       restrictions => 'NOT NULL'  },
                    531:                     { name => 'student_id',
                    532:                       type => 'MEDIUMINT UNSIGNED',
                    533:                       restrictions => 'NOT NULL'  },
                    534:                     { name => 'part_id',
                    535:                       type => 'MEDIUMINT UNSIGNED',
                    536:                       restrictions => 'NOT NULL' },
1.73      matthew   537:                     { name => 'part',
                    538:                       type => 'VARCHAR(100)',
                    539:                       restrictions => 'NOT NULL'},                    
1.57      matthew   540:                     { name => 'solved',
                    541:                       type => 'TINYTEXT' },
                    542:                     { name => 'tries',
                    543:                       type => 'SMALLINT UNSIGNED' },
                    544:                     { name => 'awarded',
                    545:                       type => 'TINYTEXT' },
                    546:                     { name => 'award',
                    547:                       type => 'TINYTEXT' },
                    548:                     { name => 'awarddetail',
                    549:                       type => 'TINYTEXT' },
                    550:                     { name => 'timestamp',
                    551:                       type => 'INT UNSIGNED'},
                    552:                     ],
                    553:         'PRIMARY KEY' => ['symb_id','student_id','part_id'],
                    554:         'KEY' => [{ columns=>['student_id'] },
                    555:                   { columns=>['symb_id'] },],
                    556:     };
                    557:     #
                    558:     my $parameters_table_def = {
                    559:         id => $parameters_table,
                    560:         permanent => 'no',
                    561:         columns => [{ name => 'symb_id',
                    562:                       type => 'MEDIUMINT UNSIGNED',
                    563:                       restrictions => 'NOT NULL'  },
                    564:                     { name => 'student_id',
                    565:                       type => 'MEDIUMINT UNSIGNED',
                    566:                       restrictions => 'NOT NULL'  },
                    567:                     { name => 'parameter',
                    568:                       type => 'TINYTEXT',
                    569:                       restrictions => 'NOT NULL'  },
                    570:                     { name => 'value',
                    571:                       type => 'MEDIUMTEXT' },
                    572:                     ],
                    573:         'PRIMARY KEY' => ['symb_id','student_id','parameter (255)'],
                    574:     };
                    575:     #
                    576:     # Create the tables
                    577:     my $tableid;
                    578:     $tableid = &Apache::lonmysql::create_table($symb_table_def);
                    579:     if (! defined($tableid)) {
                    580:         &Apache::lonnet::logthis("error creating symb_table: ".
                    581:                                  &Apache::lonmysql::get_error());
                    582:         return 1;
                    583:     }
                    584:     #
                    585:     $tableid = &Apache::lonmysql::create_table($part_table_def);
                    586:     if (! defined($tableid)) {
                    587:         &Apache::lonnet::logthis("error creating part_table: ".
                    588:                                  &Apache::lonmysql::get_error());
                    589:         return 2;
                    590:     }
                    591:     #
                    592:     $tableid = &Apache::lonmysql::create_table($student_table_def);
                    593:     if (! defined($tableid)) {
                    594:         &Apache::lonnet::logthis("error creating student_table: ".
                    595:                                  &Apache::lonmysql::get_error());
                    596:         return 3;
                    597:     }
                    598:     #
                    599:     $tableid = &Apache::lonmysql::create_table($updatetime_table_def);
                    600:     if (! defined($tableid)) {
                    601:         &Apache::lonnet::logthis("error creating updatetime_table: ".
                    602:                                  &Apache::lonmysql::get_error());
                    603:         return 4;
                    604:     }
                    605:     #
                    606:     $tableid = &Apache::lonmysql::create_table($performance_table_def);
                    607:     if (! defined($tableid)) {
                    608:         &Apache::lonnet::logthis("error creating preformance_table: ".
                    609:                                  &Apache::lonmysql::get_error());
                    610:         return 5;
                    611:     }
                    612:     #
                    613:     $tableid = &Apache::lonmysql::create_table($parameters_table_def);
                    614:     if (! defined($tableid)) {
                    615:         &Apache::lonnet::logthis("error creating parameters_table: ".
                    616:                                  &Apache::lonmysql::get_error());
                    617:         return 6;
                    618:     }
                    619:     return 0;
1.70      matthew   620: }
                    621: 
                    622: ################################################
                    623: ################################################
                    624: 
                    625: =pod
                    626: 
                    627: =item &delete_caches()
                    628: 
                    629: =cut
                    630: 
                    631: ################################################
                    632: ################################################
                    633: sub delete_caches {
                    634:     my $courseid = shift;
                    635:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
                    636:     #
                    637:     &setup_table_names($courseid);
                    638:     #
                    639:     my $dbh = &Apache::lonmysql::get_dbh();
                    640:     foreach my $table ($symb_table,$part_table,$student_table,
                    641:                        $updatetime_table,$performance_table,
                    642:                        $parameters_table ){
                    643:         my $command = 'DROP TABLE '.$table.';';
                    644:         $dbh->do($command);
                    645:         if ($dbh->err) {
                    646:             &Apache::lonnet::logthis($command.' resulted in error: '.$dbh->errstr);
                    647:         }
                    648:     }
                    649:     return;
1.57      matthew   650: }
                    651: 
                    652: ################################################
                    653: ################################################
                    654: 
                    655: =pod
                    656: 
                    657: =item &get_part_id()
                    658: 
                    659: Get the MySQL id of a problem part string.
                    660: 
                    661: Input: $part
                    662: 
                    663: Output: undef on error, integer $part_id on success.
                    664: 
                    665: =item &get_part()
                    666: 
                    667: Get the string describing a part from the MySQL id of the problem part.
                    668: 
                    669: Input: $part_id
                    670: 
                    671: Output: undef on error, $part string on success.
                    672: 
                    673: =cut
                    674: 
                    675: ################################################
                    676: ################################################
                    677: 
1.61      matthew   678: my $have_read_part_table = 0;
1.57      matthew   679: my %ids_by_part;
                    680: my %parts_by_id;
                    681: 
                    682: sub get_part_id {
                    683:     my ($part) = @_;
1.61      matthew   684:     $part = 0 if (! defined($part));
                    685:     if (! $have_read_part_table) {
                    686:         my @Result = &Apache::lonmysql::get_rows($part_table);
                    687:         foreach (@Result) {
                    688:             $ids_by_part{$_->[1]}=$_->[0];
                    689:         }
                    690:         $have_read_part_table = 1;
                    691:     }
1.57      matthew   692:     if (! exists($ids_by_part{$part})) {
                    693:         &Apache::lonmysql::store_row($part_table,[undef,$part]);
                    694:         undef(%ids_by_part);
                    695:         my @Result = &Apache::lonmysql::get_rows($part_table);
                    696:         foreach (@Result) {
                    697:             $ids_by_part{$_->[1]}=$_->[0];
                    698:         }
                    699:     }
                    700:     return $ids_by_part{$part} if (exists($ids_by_part{$part}));
                    701:     return undef; # error
                    702: }
                    703: 
                    704: sub get_part {
                    705:     my ($part_id) = @_;
                    706:     if (! exists($parts_by_id{$part_id})  || 
                    707:         ! defined($parts_by_id{$part_id}) ||
                    708:         $parts_by_id{$part_id} eq '') {
                    709:         my @Result = &Apache::lonmysql::get_rows($part_table);
                    710:         foreach (@Result) {
                    711:             $parts_by_id{$_->[0]}=$_->[1];
                    712:         }
                    713:     }
                    714:     return $parts_by_id{$part_id} if(exists($parts_by_id{$part_id}));
                    715:     return undef; # error
                    716: }
                    717: 
                    718: ################################################
                    719: ################################################
                    720: 
                    721: =pod
                    722: 
                    723: =item &get_symb_id()
                    724: 
                    725: Get the MySQL id of a symb.
                    726: 
                    727: Input: $symb
                    728: 
                    729: Output: undef on error, integer $symb_id on success.
                    730: 
                    731: =item &get_symb()
                    732: 
                    733: Get the symb associated with a MySQL symb_id.
                    734: 
                    735: Input: $symb_id
                    736: 
                    737: Output: undef on error, $symb on success.
                    738: 
                    739: =cut
                    740: 
                    741: ################################################
                    742: ################################################
                    743: 
1.61      matthew   744: my $have_read_symb_table = 0;
1.57      matthew   745: my %ids_by_symb;
                    746: my %symbs_by_id;
                    747: 
                    748: sub get_symb_id {
                    749:     my ($symb) = @_;
1.61      matthew   750:     if (! $have_read_symb_table) {
                    751:         my @Result = &Apache::lonmysql::get_rows($symb_table);
                    752:         foreach (@Result) {
                    753:             $ids_by_symb{$_->[1]}=$_->[0];
                    754:         }
                    755:         $have_read_symb_table = 1;
                    756:     }
1.57      matthew   757:     if (! exists($ids_by_symb{$symb})) {
                    758:         &Apache::lonmysql::store_row($symb_table,[undef,$symb]);
                    759:         undef(%ids_by_symb);
                    760:         my @Result = &Apache::lonmysql::get_rows($symb_table);
                    761:         foreach (@Result) {
                    762:             $ids_by_symb{$_->[1]}=$_->[0];
                    763:         }
                    764:     }
                    765:     return $ids_by_symb{$symb} if(exists( $ids_by_symb{$symb}));
                    766:     return undef; # error
                    767: }
                    768: 
                    769: sub get_symb {
                    770:     my ($symb_id) = @_;
                    771:     if (! exists($symbs_by_id{$symb_id})  || 
                    772:         ! defined($symbs_by_id{$symb_id}) ||
                    773:         $symbs_by_id{$symb_id} eq '') {
                    774:         my @Result = &Apache::lonmysql::get_rows($symb_table);
                    775:         foreach (@Result) {
                    776:             $symbs_by_id{$_->[0]}=$_->[1];
                    777:         }
                    778:     }
                    779:     return $symbs_by_id{$symb_id} if(exists( $symbs_by_id{$symb_id}));
                    780:     return undef; # error
                    781: }
                    782: 
                    783: ################################################
                    784: ################################################
                    785: 
                    786: =pod
                    787: 
                    788: =item &get_student_id()
                    789: 
                    790: Get the MySQL id of a student.
                    791: 
                    792: Input: $sname, $dom
                    793: 
                    794: Output: undef on error, integer $student_id on success.
                    795: 
                    796: =item &get_student()
                    797: 
                    798: Get student username:domain associated with the MySQL student_id.
                    799: 
                    800: Input: $student_id
                    801: 
                    802: Output: undef on error, string $student (username:domain) on success.
                    803: 
                    804: =cut
                    805: 
                    806: ################################################
                    807: ################################################
                    808: 
1.61      matthew   809: my $have_read_student_table = 0;
1.57      matthew   810: my %ids_by_student;
                    811: my %students_by_id;
                    812: 
                    813: sub get_student_id {
                    814:     my ($sname,$sdom) = @_;
                    815:     my $student = $sname.':'.$sdom;
1.61      matthew   816:     if (! $have_read_student_table) {
                    817:         my @Result = &Apache::lonmysql::get_rows($student_table);
                    818:         foreach (@Result) {
                    819:             $ids_by_student{$_->[1]}=$_->[0];
                    820:         }
                    821:         $have_read_student_table = 1;
                    822:     }
1.57      matthew   823:     if (! exists($ids_by_student{$student})) {
                    824:         &Apache::lonmysql::store_row($student_table,[undef,$student]);
                    825:         undef(%ids_by_student);
                    826:         my @Result = &Apache::lonmysql::get_rows($student_table);
                    827:         foreach (@Result) {
                    828:             $ids_by_student{$_->[1]}=$_->[0];
                    829:         }
                    830:     }
                    831:     return $ids_by_student{$student} if(exists( $ids_by_student{$student}));
                    832:     return undef; # error
                    833: }
                    834: 
                    835: sub get_student {
                    836:     my ($student_id) = @_;
                    837:     if (! exists($students_by_id{$student_id})  || 
                    838:         ! defined($students_by_id{$student_id}) ||
                    839:         $students_by_id{$student_id} eq '') {
                    840:         my @Result = &Apache::lonmysql::get_rows($student_table);
                    841:         foreach (@Result) {
                    842:             $students_by_id{$_->[0]}=$_->[1];
                    843:         }
                    844:     }
                    845:     return $students_by_id{$student_id} if(exists($students_by_id{$student_id}));
                    846:     return undef; # error
                    847: }
                    848: 
                    849: ################################################
                    850: ################################################
                    851: 
                    852: =pod
                    853: 
                    854: =item &update_student_data()
                    855: 
                    856: Input: $sname, $sdom, $courseid
                    857: 
                    858: Output: $returnstatus, \%student_data
                    859: 
                    860: $returnstatus is a string describing any errors that occured.  'okay' is the
                    861: default.
                    862: \%student_data is the data returned by a call to lonnet::currentdump.
                    863: 
                    864: This subroutine loads a students data using lonnet::currentdump and inserts
                    865: it into the MySQL database.  The inserts are done on two tables, 
                    866: $performance_table and $parameters_table.  $parameters_table holds the data 
                    867: that is not included in $performance_table.  See the description of 
                    868: $performance_table elsewhere in this file.  The INSERT calls are made
                    869: directly by this subroutine, not through lonmysql because we do a 'bulk'
                    870: insert which takes advantage of MySQLs non-SQL compliant INSERT command to 
                    871: insert multiple rows at a time.  If anything has gone wrong during this
                    872: process, $returnstatus is updated with a description of the error and
                    873: \%student_data is returned.  
                    874: 
                    875: Notice we do not insert the data and immediately query it.  This means it
                    876: is possible for there to be data returned this first time that is not 
                    877: available the second time.  CYA.
                    878: 
                    879: =cut
                    880: 
                    881: ################################################
                    882: ################################################
                    883: sub update_student_data {
                    884:     my ($sname,$sdom,$courseid) = @_;
                    885:     #
1.60      matthew   886:     # Set up database names
                    887:     &setup_table_names($courseid);
                    888:     #
1.57      matthew   889:     my $student_id = &get_student_id($sname,$sdom);
                    890:     my $student = $sname.':'.$sdom;
                    891:     #
                    892:     my $returnstatus = 'okay';
                    893:     #
                    894:     # Download students data
                    895:     my $time_of_retrieval = time;
                    896:     my @tmp = &Apache::lonnet::currentdump($courseid,$sdom,$sname);
                    897:     if ((scalar(@tmp) > 0) && ($tmp[0] =~ /^error:/)) {
                    898:         &Apache::lonnet::logthis('error getting data for '.
                    899:                                  $sname.':'.$sdom.' in course '.$courseid.
                    900:                                  ':'.$tmp[0]);
                    901:         $returnstatus = 'error getting data';
                    902:         return $returnstatus;
                    903:     }
                    904:     if (scalar(@tmp) < 1) {
                    905:         return ('no data',undef);
                    906:     }
                    907:     my %student_data = @tmp;
                    908:     #
                    909:     # Remove all of the students data from the table
1.60      matthew   910:     my $dbh = &Apache::lonmysql::get_dbh();
                    911:     $dbh->do('DELETE FROM '.$performance_table.' WHERE student_id='.
                    912:              $student_id);
                    913:     $dbh->do('DELETE FROM '.$parameters_table.' WHERE student_id='.
                    914:              $student_id);
1.57      matthew   915:     #
                    916:     # Store away the data
                    917:     #
                    918:     my $starttime = Time::HiRes::time;
                    919:     my $elapsed = 0;
                    920:     my $rows_stored;
                    921:     my $store_parameters_command  = 'INSERT INTO '.$parameters_table.
1.60      matthew   922:         ' VALUES '."\n";
1.61      matthew   923:     my $num_parameters = 0;
1.57      matthew   924:     my $store_performance_command = 'INSERT INTO '.$performance_table.
1.60      matthew   925:         ' VALUES '."\n";
1.57      matthew   926:     return 'error' if (! defined($dbh));
                    927:     while (my ($current_symb,$param_hash) = each(%student_data)) {
                    928:         #
                    929:         # make sure the symb is set up properly
                    930:         my $symb_id = &get_symb_id($current_symb);
                    931:         #
                    932:         # Load data into the tables
1.63      matthew   933:         while (my ($parameter,$value) = each(%$param_hash)) {
1.57      matthew   934:             my $newstring;
1.63      matthew   935:             if ($parameter !~ /(timestamp|resource\.(.*)\.(solved|tries|awarded|award|awarddetail|previous))/) {
1.57      matthew   936:                 $newstring = "('".join("','",
                    937:                                        $symb_id,$student_id,
1.69      matthew   938:                                        $parameter)."',".
                    939:                                            $dbh->quote($value)."),\n";
1.61      matthew   940:                 $num_parameters ++;
1.57      matthew   941:                 if ($newstring !~ /''/) {
                    942:                     $store_parameters_command .= $newstring;
                    943:                     $rows_stored++;
                    944:                 }
                    945:             }
                    946:             next if ($parameter !~ /^resource\.(.*)\.solved$/);
                    947:             #
                    948:             my $part = $1;
                    949:             my $part_id = &get_part_id($part);
                    950:             next if (!defined($part_id));
                    951:             my $solved  = $value;
                    952:             my $tries   = $param_hash->{'resource.'.$part.'.tries'};
                    953:             my $awarded = $param_hash->{'resource.'.$part.'.awarded'};
                    954:             my $award   = $param_hash->{'resource.'.$part.'.award'};
                    955:             my $awarddetail = $param_hash->{'resource.'.$part.'.awarddetail'};
                    956:             my $timestamp = $param_hash->{'timestamp'};
1.60      matthew   957:             #
1.74    ! matthew   958:             $solved      = '' if (! defined($solved));
1.57      matthew   959:             $tries       = '' if (! defined($tries));
                    960:             $awarded     = '' if (! defined($awarded));
                    961:             $award       = '' if (! defined($award));
                    962:             $awarddetail = '' if (! defined($awarddetail));
1.73      matthew   963:             $newstring = "('".join("','",$symb_id,$student_id,$part_id,$part,
1.57      matthew   964:                                    $solved,$tries,$awarded,$award,
1.63      matthew   965:                                    $awarddetail,$timestamp)."'),\n";
1.57      matthew   966:             $store_performance_command .= $newstring;
                    967:             $rows_stored++;
                    968:         }
                    969:     }
                    970:     chop $store_parameters_command;
1.60      matthew   971:     chop $store_parameters_command;
                    972:     chop $store_performance_command;
1.57      matthew   973:     chop $store_performance_command;
                    974:     my $start = Time::HiRes::time;
1.61      matthew   975:     $dbh->do($store_parameters_command) if ($num_parameters>0);
1.57      matthew   976:     if ($dbh->err()) {
                    977:         &Apache::lonnet::logthis(' bigass insert error:'.$dbh->errstr());
1.61      matthew   978:         &Apache::lonnet::logthis('command = '.$store_parameters_command);
1.57      matthew   979:         $returnstatus = 'error: unable to insert parameters into database';
                    980:         return $returnstatus,\%student_data;
                    981:     }
                    982:     $dbh->do($store_performance_command);
                    983:     if ($dbh->err()) {
                    984:         &Apache::lonnet::logthis(' bigass insert error:'.$dbh->errstr());
1.61      matthew   985:         &Apache::lonnet::logthis('command = '.$store_performance_command);
1.57      matthew   986:         $returnstatus = 'error: unable to insert performance into database';
                    987:         return $returnstatus,\%student_data;
                    988:     }
                    989:     $elapsed += Time::HiRes::time - $start;
                    990:     #
                    991:     # Set the students update time
                    992:     &Apache::lonmysql::replace_row($updatetime_table,
                    993:                                    [$student,$time_of_retrieval]);
                    994:     return ($returnstatus,\%student_data);
                    995: }
                    996: 
                    997: ################################################
                    998: ################################################
                    999: 
                   1000: =pod
                   1001: 
                   1002: =item &ensure_current_data()
                   1003: 
                   1004: Input: $sname, $sdom, $courseid
                   1005: 
                   1006: Output: $status, $data
                   1007: 
                   1008: This routine ensures the data for a given student is up to date.  It calls
                   1009: &init_dbs() if the tables do not exist.  The $updatetime_table is queried
                   1010: to determine the time of the last update.  If the students data is out of
                   1011: date, &update_student_data() is called.  The return values from the call
                   1012: to &update_student_data() are returned.
                   1013: 
                   1014: =cut
                   1015: 
                   1016: ################################################
                   1017: ################################################
                   1018: sub ensure_current_data {
                   1019:     my ($sname,$sdom,$courseid) = @_;
                   1020:     my $status = 'okay';   # return value
                   1021:     #
1.61      matthew  1022:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
                   1023:     # 
                   1024:     # Clean out package variables
1.57      matthew  1025:     &setup_table_names($courseid);
                   1026:     #
                   1027:     # if the tables do not exist, make them
                   1028:     my @CurrentTable = &Apache::lonmysql::tables_in_db();
                   1029:     my ($found_symb,$found_student,$found_part,$found_update,
                   1030:         $found_performance,$found_parameters);
                   1031:     foreach (@CurrentTable) {
                   1032:         $found_symb        = 1 if ($_ eq $symb_table);
                   1033:         $found_student     = 1 if ($_ eq $student_table);
                   1034:         $found_part        = 1 if ($_ eq $part_table);
                   1035:         $found_update      = 1 if ($_ eq $updatetime_table);
                   1036:         $found_performance = 1 if ($_ eq $performance_table);
                   1037:         $found_parameters  = 1 if ($_ eq $parameters_table);
                   1038:     }
                   1039:     if (!$found_symb        || !$found_update || 
                   1040:         !$found_student     || !$found_part   ||
                   1041:         !$found_performance || !$found_parameters) {
                   1042:         if (&init_dbs($courseid)) {
                   1043:             return 'error';
                   1044:         }
                   1045:     }
                   1046:     #
                   1047:     # Get the update time for the user
                   1048:     my $updatetime = 0;
1.60      matthew  1049:     my $modifiedtime = &Apache::lonnet::GetFileTimestamp
                   1050:         ($sdom,$sname,$courseid.'.db',
                   1051:          $Apache::lonnet::perlvar{'lonUsersDir'});
1.57      matthew  1052:     #
                   1053:     my $student = $sname.':'.$sdom;
                   1054:     my @Result = &Apache::lonmysql::get_rows($updatetime_table,
                   1055:                                              "student ='$student'");
                   1056:     my $data = undef;
                   1057:     if (@Result) {
                   1058:         $updatetime = $Result[0]->[1];
                   1059:     }
                   1060:     if ($modifiedtime > $updatetime) {
                   1061:         ($status,$data) = &update_student_data($sname,$sdom,$courseid);
                   1062:     }
                   1063:     return ($status,$data);
                   1064: }
                   1065: 
                   1066: ################################################
                   1067: ################################################
                   1068: 
                   1069: =pod
                   1070: 
                   1071: =item &get_student_data_from_performance_cache()
                   1072: 
                   1073: Input: $sname, $sdom, $symb, $courseid
                   1074: 
                   1075: Output: hash reference containing the data for the given student.
                   1076: If $symb is undef, all the students data is returned.
                   1077: 
                   1078: This routine is the heart of the local caching system.  See the description
                   1079: of $performance_table, $symb_table, $student_table, and $part_table.  The
                   1080: main task is building the MySQL request.  The tables appear in the request
                   1081: in the order in which they should be parsed by MySQL.  When searching
                   1082: on a student the $student_table is used to locate the 'student_id'.  All
                   1083: rows in $performance_table which have a matching 'student_id' are returned,
                   1084: with data from $part_table and $symb_table which match the entries in
                   1085: $performance_table, 'part_id' and 'symb_id'.  When searching on a symb,
                   1086: the $symb_table is processed first, with matching rows grabbed from 
                   1087: $performance_table and filled in from $part_table and $student_table in
                   1088: that order.  
                   1089: 
                   1090: Running 'EXPLAIN ' on the 'SELECT' statements generated can be quite 
                   1091: interesting, especially if you play with the order the tables are listed.  
                   1092: 
                   1093: =cut
                   1094: 
                   1095: ################################################
                   1096: ################################################
                   1097: sub get_student_data_from_performance_cache {
                   1098:     my ($sname,$sdom,$symb,$courseid)=@_;
                   1099:     my $student = $sname.':'.$sdom if (defined($sname) && defined($sdom));
1.61      matthew  1100:     &setup_table_names($courseid);
1.57      matthew  1101:     #
                   1102:     # Return hash
                   1103:     my $studentdata;
                   1104:     #
                   1105:     my $dbh = &Apache::lonmysql::get_dbh();
                   1106:     my $request = "SELECT ".
1.73      matthew  1107:         "d.symb,a.part,a.solved,a.tries,a.awarded,a.award,a.awarddetail,".
1.63      matthew  1108:             "a.timestamp ";
1.57      matthew  1109:     if (defined($student)) {
                   1110:         $request .= "FROM $student_table AS b ".
                   1111:             "LEFT JOIN $performance_table AS a ON b.student_id=a.student_id ".
1.73      matthew  1112: #            "LEFT JOIN $part_table AS c ON c.part_id = a.part_id ".
1.57      matthew  1113:             "LEFT JOIN $symb_table AS d ON d.symb_id = a.symb_id ".
                   1114:                 "WHERE student='$student'";
                   1115:         if (defined($symb) && $symb ne '') {
1.67      matthew  1116:             $request .= " AND d.symb=".$dbh->quote($symb);
1.57      matthew  1117:         }
                   1118:     } elsif (defined($symb) && $symb ne '') {
                   1119:         $request .= "FROM $symb_table as d ".
                   1120:             "LEFT JOIN $performance_table AS a ON d.symb_id=a.symb_id ".
1.73      matthew  1121: #            "LEFT JOIN $part_table    AS c ON c.part_id = a.part_id ".
1.57      matthew  1122:             "LEFT JOIN $student_table AS b ON b.student_id = a.student_id ".
                   1123:                 "WHERE symb='".$dbh->quote($symb)."'";
                   1124:     }
                   1125:     my $starttime = Time::HiRes::time;
                   1126:     my $rows_retrieved = 0;
                   1127:     my $sth = $dbh->prepare($request);
                   1128:     $sth->execute();
                   1129:     if ($sth->err()) {
                   1130:         &Apache::lonnet::logthis("Unable to execute MySQL request:");
                   1131:         &Apache::lonnet::logthis("\n".$request."\n");
                   1132:         &Apache::lonnet::logthis("error is:".$sth->errstr());
                   1133:         return undef;
                   1134:     }
                   1135:     foreach my $row (@{$sth->fetchall_arrayref}) {
                   1136:         $rows_retrieved++;
1.63      matthew  1137:         my ($symb,$part,$solved,$tries,$awarded,$award,$awarddetail,$time) = 
1.57      matthew  1138:             (@$row);
                   1139:         my $base = 'resource.'.$part;
                   1140:         $studentdata->{$symb}->{$base.'.solved'}  = $solved;
                   1141:         $studentdata->{$symb}->{$base.'.tries'}   = $tries;
                   1142:         $studentdata->{$symb}->{$base.'.awarded'} = $awarded;
                   1143:         $studentdata->{$symb}->{$base.'.award'}   = $award;
                   1144:         $studentdata->{$symb}->{$base.'.awarddetail'} = $awarddetail;
                   1145:         $studentdata->{$symb}->{'timestamp'} = $time if (defined($time) && $time ne '');
1.67      matthew  1146:     }
                   1147:     if (defined($symb) && $symb ne '') {
                   1148:         $studentdata = $studentdata->{$symb};
1.57      matthew  1149:     }
                   1150:     return $studentdata;
                   1151: }
                   1152: 
                   1153: ################################################
                   1154: ################################################
                   1155: 
                   1156: =pod
                   1157: 
                   1158: =item &get_current_state()
                   1159: 
                   1160: Input: $sname,$sdom,$symb,$courseid
                   1161: 
                   1162: Output: Described below
1.46      matthew  1163: 
1.47      matthew  1164: Retrieve the current status of a students performance.  $sname and
1.46      matthew  1165: $sdom are the only required parameters.  If $symb is undef the results
1.47      matthew  1166: of an &Apache::lonnet::currentdump() will be returned.  
1.46      matthew  1167: If $courseid is undef it will be retrieved from the environment.
                   1168: 
                   1169: The return structure is based on &Apache::lonnet::currentdump.  If
                   1170: $symb is unspecified, all the students data is returned in a hash of
                   1171: the form:
                   1172: ( 
                   1173:   symb1 => { param1 => value1, param2 => value2 ... },
                   1174:   symb2 => { param1 => value1, param2 => value2 ... },
                   1175: )
                   1176: 
                   1177: If $symb is specified, a hash of 
                   1178: (
                   1179:   param1 => value1, 
                   1180:   param2 => value2,
                   1181: )
                   1182: is returned.
                   1183: 
1.57      matthew  1184: If no data is found for $symb, or if the student has no performance data,
1.46      matthew  1185: an empty list is returned.
                   1186: 
                   1187: =cut
                   1188: 
                   1189: ################################################
                   1190: ################################################
                   1191: sub get_current_state {
1.47      matthew  1192:     my ($sname,$sdom,$symb,$courseid,$forcedownload)=@_;
                   1193:     #
1.46      matthew  1194:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
1.47      matthew  1195:     #
1.61      matthew  1196:     return () if (! defined($sname) || ! defined($sdom));
                   1197:     #
1.57      matthew  1198:     my ($status,$data) = &ensure_current_data($sname,$sdom,$courseid);
1.72      matthew  1199:     &Apache::lonnet::logthis
                   1200:         ('sname = '.$sname.
                   1201:          ' domain = '.$sdom.
                   1202:          ' status = '.$status.
                   1203:          ' data is '.(defined($data)?'defined':'undefined'));
1.73      matthew  1204: #    while (my ($symb,$hash) = each(%$data)) {
                   1205: #        &Apache::lonnet::logthis($symb."\n----------------------------------");
                   1206: #        while (my ($key,$value) = each (%$hash)) {
                   1207: #            &Apache::lonnet::logthis("   ".$key." = ".$value);
                   1208: #        }
                   1209: #    }
1.47      matthew  1210:     #
1.57      matthew  1211:     if (defined($data)) {
1.68      matthew  1212:         if (defined($symb)) {
                   1213:             return %{$data->{$symb}};
                   1214:         } else {
                   1215:             return %$data;
                   1216:         }
1.57      matthew  1217:     } elsif ($status eq 'no data') {
                   1218:         return ();
                   1219:     } else {
                   1220:         if ($status ne 'okay' && $status ne '') {
                   1221:             &Apache::lonnet::logthis('status = '.$status);
1.47      matthew  1222:             return ();
                   1223:         }
1.57      matthew  1224:         my $returnhash = &get_student_data_from_performance_cache($sname,$sdom,
                   1225:                                                       $symb,$courseid);
                   1226:         return %$returnhash if (defined($returnhash));
1.46      matthew  1227:     }
1.57      matthew  1228:     return ();
1.61      matthew  1229: }
                   1230: 
                   1231: ################################################
                   1232: ################################################
                   1233: 
                   1234: =pod
                   1235: 
                   1236: =item &get_problem_statistics()
                   1237: 
                   1238: Gather data on a given problem.  The database is assumed to be 
                   1239: populated and all local caching variables are assumed to be set
                   1240: properly.  This means you need to call &ensure_current_data for
                   1241: the students you are concerned with prior to calling this routine.
                   1242: 
                   1243: Inputs: $students, $symb, $part, $courseid
                   1244: 
1.64      matthew  1245: =over 4
                   1246: 
                   1247: =item $students is an array of hash references.  
                   1248: Each hash must contain at least the 'username' and 'domain' of a student.
                   1249: 
                   1250: =item $symb is the symb for the problem.
                   1251: 
                   1252: =item $part is the part id you need statistics for
                   1253: 
                   1254: =item $courseid is the course id, of course!
                   1255: 
                   1256: =back
                   1257: 
1.66      matthew  1258: Outputs: See the code for up to date information.  A hash reference is
                   1259: returned.  The hash has the following keys defined:
1.64      matthew  1260: 
                   1261: =over 4
                   1262: 
1.66      matthew  1263: =item num_students The number of students attempting the problem
                   1264:       
                   1265: =item tries The total number of tries for the students
                   1266:       
                   1267: =item max_tries The maximum number of tries taken
                   1268:       
                   1269: =item mean_tries The average number of tries
                   1270:       
                   1271: =item num_solved The number of students able to solve the problem
                   1272:       
                   1273: =item num_override The number of students whose answer is 'correct_by_override'
                   1274:       
                   1275: =item deg_of_diff The degree of difficulty of the problem
                   1276:       
                   1277: =item std_tries The standard deviation of the number of tries
                   1278:       
                   1279: =item skew_tries The skew of the number of tries
1.64      matthew  1280: 
1.66      matthew  1281: =item per_wrong The number of students attempting the problem who were not
                   1282: able to answer it correctly.
1.64      matthew  1283: 
                   1284: =back
                   1285: 
1.61      matthew  1286: =cut
                   1287: 
                   1288: ################################################
                   1289: ################################################
                   1290: sub get_problem_statistics {
                   1291:     my ($students,$symb,$part,$courseid) = @_;
                   1292:     return if (! defined($symb) || ! defined($part));
                   1293:     $courseid = $ENV{'request.course.id'} if (! defined($courseid));
                   1294:     #
                   1295:     my $symb_id = &get_symb_id($symb);
                   1296:     my $part_id = &get_part_id($part);
                   1297:     my $stats_table = $courseid.'_problem_stats';
                   1298:     #
                   1299:     my $dbh = &Apache::lonmysql::get_dbh();
                   1300:     return undef if (! defined($dbh));
                   1301:     #
                   1302:     # A) Number of Students attempting problem
                   1303:     # B) Total number of tries of students attempting problem
                   1304:     # C) Mod (largest number of tries for solving the problem)
                   1305:     # D) Mean (average number of tries for solving the problem)
                   1306:     # E) Number of students to solve the problem
                   1307:     # F) Number of students to solve the problem by override
                   1308:     # G) Number of students unable to solve the problem
                   1309:     # H) Degree of difficulty : 1-(E+F)/B
                   1310:     # I) Standard deviation of number of tries
                   1311:     # J) Skew of tries: sqrt(sum(Xi-D)^3)/A
                   1312:     #
                   1313:     $dbh->do('DROP TABLE '.$stats_table);  # May return an error
                   1314:     my $request = 
                   1315:         'CREATE TEMPORARY TABLE '.$stats_table.
                   1316:             ' SELECT student_id,solved,award,tries FROM '.$performance_table.
                   1317:                 ' WHERE symb_id='.$symb_id.' AND part_id='.$part_id;
1.64      matthew  1318:     if (defined($students)) {
                   1319:         $request .= ' AND ('.
                   1320:             join(' OR ', map {'student_id='.
                   1321:                                   &get_student_id($_->{'username'},
                   1322:                                                   $_->{'domain'})
                   1323:                                   } @$students
                   1324:                  ).')';
                   1325:     }
1.61      matthew  1326: #    &Apache::lonnet::logthis($request);
                   1327:     $dbh->do($request);
                   1328:     my ($num,$tries,$mod,$mean,$STD) = &execute_SQL_request
                   1329:         ($dbh,
                   1330:          'SELECT COUNT(*),SUM(tries),MAX(tries),AVG(tries),STD(tries) FROM '.
                   1331:          $stats_table);
                   1332:     my ($Solved) = &execute_SQL_request($dbh,'SELECT COUNT(tries) FROM '.
                   1333:                                         $stats_table.
                   1334:                                         " WHERE solved='correct_by_student'");
                   1335:     my ($solved) = &execute_SQL_request($dbh,'SELECT COUNT(tries) FROM '.
                   1336:                                         $stats_table.
                   1337:                                         " WHERE solved='correct_by_override'");
                   1338:     $num    = 0 if (! defined($num));
                   1339:     $tries  = 0 if (! defined($tries));
                   1340:     $mod    = 0 if (! defined($mod));
                   1341:     $STD    = 0 if (! defined($STD));
                   1342:     $Solved = 0 if (! defined($Solved));
                   1343:     $solved = 0 if (! defined($solved));
                   1344:     #
                   1345:     my $DegOfDiff = 'nan';
1.66      matthew  1346:     $DegOfDiff = 1-($Solved)/$tries if ($tries>0);
1.61      matthew  1347: 
                   1348:     my $SKEW = 'nan';
1.66      matthew  1349:     my $wrongpercent = 0;
1.61      matthew  1350:     if ($num > 0) {
                   1351:         ($SKEW) = &execute_SQL_request($dbh,'SELECT SQRT(SUM('.
                   1352:                                      'POWER(tries - '.$STD.',3)'.
                   1353:                                      '))/'.$num.' FROM '.$stats_table);
1.66      matthew  1354:         $wrongpercent=int(10*100*($num-$Solved+$solved)/$num)/10;
1.61      matthew  1355:     }
                   1356:     #
                   1357:     $dbh->do('DROP TABLE '.$stats_table);  # May return an error
1.66      matthew  1358:     return { num_students => $num,
                   1359:              tries        => $tries,
                   1360:              max_tries    => $mod,
                   1361:              mean_tries   => $mean,
                   1362:              std_tries    => $STD,
                   1363:              skew_tries   => $SKEW,
                   1364:              num_solved   => $Solved,
                   1365:              num_override => $solved,
                   1366:              per_wrong    => $wrongpercent,
                   1367:              deg_of_diff  => $DegOfDiff }
1.61      matthew  1368: }
                   1369: 
                   1370: sub execute_SQL_request {
                   1371:     my ($dbh,$request)=@_;
                   1372: #    &Apache::lonnet::logthis($request);
                   1373:     my $sth = $dbh->prepare($request);
                   1374:     $sth->execute();
                   1375:     my $row = $sth->fetchrow_arrayref();
                   1376:     if (ref($row) eq 'ARRAY' && scalar(@$row)>0) {
                   1377:         return @$row;
                   1378:     }
                   1379:     return ();
                   1380: }
                   1381: 
                   1382: 
                   1383: ################################################
                   1384: ################################################
                   1385: 
                   1386: =pod
                   1387: 
                   1388: =item &setup_table_names()
                   1389: 
                   1390: input: course id
                   1391: 
                   1392: output: none
                   1393: 
                   1394: Cleans up the package variables for local caching.
                   1395: 
                   1396: =cut
                   1397: 
                   1398: ################################################
                   1399: ################################################
                   1400: sub setup_table_names {
                   1401:     my ($courseid) = @_;
                   1402:     if (! defined($courseid)) {
                   1403:         $courseid = $ENV{'request.course.id'};
                   1404:     }
                   1405:     #
                   1406:     if (! defined($current_course) || $current_course ne $courseid) {
                   1407:         # Clear out variables
                   1408:         $have_read_part_table = 0;
                   1409:         undef(%ids_by_part);
                   1410:         undef(%parts_by_id);
                   1411:         $have_read_symb_table = 0;
                   1412:         undef(%ids_by_symb);
                   1413:         undef(%symbs_by_id);
                   1414:         $have_read_student_table = 0;
                   1415:         undef(%ids_by_student);
                   1416:         undef(%students_by_id);
                   1417:         #
                   1418:         $current_course = $courseid;
                   1419:     }
                   1420:     #
                   1421:     # Set up database names
                   1422:     my $base_id = $courseid;
                   1423:     $symb_table        = $base_id.'_'.'symb';
                   1424:     $part_table        = $base_id.'_'.'part';
                   1425:     $student_table     = $base_id.'_'.'student';
                   1426:     $updatetime_table  = $base_id.'_'.'updatetime';
                   1427:     $performance_table = $base_id.'_'.'performance';
                   1428:     $parameters_table  = $base_id.'_'.'parameters';
                   1429:     return;
1.3       stredwic 1430: }
1.1       stredwic 1431: 
1.35      matthew  1432: ################################################
                   1433: ################################################
                   1434: 
                   1435: =pod
                   1436: 
1.57      matthew  1437: =back
                   1438: 
                   1439: =item End of Local Data Caching Subroutines
                   1440: 
                   1441: =cut
                   1442: 
                   1443: ################################################
                   1444: ################################################
                   1445: 
                   1446: 
                   1447: }
                   1448: ################################################
                   1449: ################################################
                   1450: 
                   1451: =pod
                   1452: 
                   1453: =head3 Classlist Subroutines
                   1454: 
1.35      matthew  1455: =item &get_classlist();
                   1456: 
                   1457: Retrieve the classist of a given class or of the current class.  Student
                   1458: information is returned from the classlist.db file and, if needed,
                   1459: from the students environment.
                   1460: 
                   1461: Optional arguments are $cid, $cdom, and $cnum (course id, course domain,
                   1462: and course number, respectively).  Any omitted arguments will be taken 
                   1463: from the current environment ($ENV{'request.course.id'},
                   1464: $ENV{'course.'.$cid.'.domain'}, and $ENV{'course.'.$cid.'.num'}).
                   1465: 
                   1466: Returns a reference to a hash which contains:
                   1467:  keys    '$sname:$sdom'
1.54      bowersj2 1468:  values  [$sdom,$sname,$end,$start,$id,$section,$fullname,$status]
                   1469: 
                   1470: The constant values CL_SDOM, CL_SNAME, CL_END, etc. can be used
                   1471: as indices into the returned list to future-proof clients against
                   1472: changes in the list order.
1.35      matthew  1473: 
                   1474: =cut
                   1475: 
                   1476: ################################################
                   1477: ################################################
1.54      bowersj2 1478: 
                   1479: sub CL_SDOM     { return 0; }
                   1480: sub CL_SNAME    { return 1; }
                   1481: sub CL_END      { return 2; }
                   1482: sub CL_START    { return 3; }
                   1483: sub CL_ID       { return 4; }
                   1484: sub CL_SECTION  { return 5; }
                   1485: sub CL_FULLNAME { return 6; }
                   1486: sub CL_STATUS   { return 7; }
1.35      matthew  1487: 
                   1488: sub get_classlist {
                   1489:     my ($cid,$cdom,$cnum) = @_;
                   1490:     $cid = $cid || $ENV{'request.course.id'};
                   1491:     $cdom = $cdom || $ENV{'course.'.$cid.'.domain'};
                   1492:     $cnum = $cnum || $ENV{'course.'.$cid.'.num'};
1.57      matthew  1493:     my $now = time;
1.35      matthew  1494:     #
                   1495:     my %classlist=&Apache::lonnet::dump('classlist',$cdom,$cnum);
                   1496:     while (my ($student,$info) = each(%classlist)) {
1.60      matthew  1497:         if ($student =~ /^(con_lost|error|no_such_host)/i) {
                   1498:             &Apache::lonnet::logthis('get_classlist error for '.$cid.':'.$student);
                   1499:             return undef;
                   1500:         }
1.35      matthew  1501:         my ($sname,$sdom) = split(/:/,$student);
                   1502:         my @Values = split(/:/,$info);
                   1503:         my ($end,$start,$id,$section,$fullname);
                   1504:         if (@Values > 2) {
                   1505:             ($end,$start,$id,$section,$fullname) = @Values;
                   1506:         } else { # We have to get the data ourselves
                   1507:             ($end,$start) = @Values;
1.37      matthew  1508:             $section = &Apache::lonnet::getsection($sdom,$sname,$cid);
1.35      matthew  1509:             my %info=&Apache::lonnet::get('environment',
                   1510:                                           ['firstname','middlename',
                   1511:                                            'lastname','generation','id'],
                   1512:                                           $sdom, $sname);
                   1513:             my ($tmp) = keys(%info);
                   1514:             if ($tmp =~/^(con_lost|error|no_such_host)/i) {
                   1515:                 $fullname = 'not available';
                   1516:                 $id = 'not available';
1.38      matthew  1517:                 &Apache::lonnet::logthis('unable to retrieve environment '.
                   1518:                                          'for '.$sname.':'.$sdom);
1.35      matthew  1519:             } else {
                   1520:                 $fullname = &ProcessFullName(@info{qw/lastname generation 
                   1521:                                                        firstname middlename/});
                   1522:                 $id = $info{'id'};
                   1523:             }
1.36      matthew  1524:             # Update the classlist with this students information
                   1525:             if ($fullname ne 'not available') {
                   1526:                 my $enrolldata = join(':',$end,$start,$id,$section,$fullname);
                   1527:                 my $reply=&Apache::lonnet::cput('classlist',
                   1528:                                                 {$student => $enrolldata},
                   1529:                                                 $cdom,$cnum);
                   1530:                 if ($reply !~ /^(ok|delayed)/) {
                   1531:                     &Apache::lonnet::logthis('Unable to update classlist for '.
                   1532:                                              'student '.$sname.':'.$sdom.
                   1533:                                              ' error:'.$reply);
                   1534:                 }
                   1535:             }
1.35      matthew  1536:         }
                   1537:         my $status='Expired';
                   1538:         if(((!$end) || $now < $end) && ((!$start) || ($now > $start))) {
                   1539:             $status='Active';
                   1540:         }
                   1541:         $classlist{$student} = 
                   1542:             [$sdom,$sname,$end,$start,$id,$section,$fullname,$status];
                   1543:     }
                   1544:     if (wantarray()) {
                   1545:         return (\%classlist,['domain','username','end','start','id',
                   1546:                              'section','fullname','status']);
                   1547:     } else {
                   1548:         return \%classlist;
                   1549:     }
                   1550: }
                   1551: 
1.1       stredwic 1552: # ----- END HELPER FUNCTIONS --------------------------------------------
                   1553: 
                   1554: 1;
                   1555: __END__
1.36      matthew  1556: 
1.35      matthew  1557: 

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