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

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

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