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

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

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