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

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

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