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

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

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