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

1.1       stredwic    1: # The LearningOnline Network with CAPA
                      2: #
1.156   ! albertel    3: # $Id: loncoursedata.pm,v 1.155 2006/02/05 19:14:58 albertel 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);
1.146     albertel   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.71      matthew    69: ################################################
                     70: ################################################
                     71: 
                     72: =pod
                     73: 
1.47      matthew    74: =item &make_into_hash($values);
                     75: 
                     76: Returns a reference to a hash as described by $values.  $values is
                     77: assumed to be the result of 
1.57      matthew    78:     join(':',map {&Apache::lonnet::escape($_)} %orighash);
1.47      matthew    79: 
                     80: This is a helper function for get_current_state.
                     81: 
                     82: =cut
                     83: 
                     84: ################################################
                     85: ################################################
                     86: sub make_into_hash {
                     87:     my $values = shift;
                     88:     my %tmp = map { &Apache::lonnet::unescape($_); }
                     89:                                            split(':',$values);
                     90:     return \%tmp;
                     91: }
                     92: 
                     93: 
                     94: ################################################
                     95: ################################################
                     96: 
                     97: =pod
                     98: 
1.57      matthew    99: =head1 LOCAL DATA CACHING SUBROUTINES
                    100: 
                    101: The local caching is done using MySQL.  There is no fall-back implementation
                    102: if MySQL is not running.
                    103: 
                    104: The programmers interface is to call &get_current_state() or some other
                    105: primary interface subroutine (described below).  The internals of this 
                    106: storage system are documented here.
                    107: 
                    108: There are six tables used to store student performance data (the results of
                    109: a dumpcurrent).  Each of these tables is created in MySQL with a name of
                    110: $courseid_*****, where ***** is 'symb', 'part', or whatever is appropriate 
                    111: for the table.  The tables and their purposes are described below.
                    112: 
                    113: Some notes before we get started.
                    114: 
                    115: Each table must have a PRIMARY KEY, which is a column or set of columns which
                    116: will serve to uniquely identify a row of data.  NULL is not allowed!
                    117: 
                    118: INDEXes work best on integer data.
                    119: 
                    120: JOIN is used to combine data from many tables into one output.
                    121: 
                    122: lonmysql.pm is used for some of the interface, specifically the table creation
                    123: calls.  The inserts are done in bulk by directly calling the database handler.
                    124: The SELECT ... JOIN statement used to retrieve the data does not have an
                    125: interface in lonmysql.pm and I shudder at the thought of writing one.
                    126: 
                    127: =head3 Table Descriptions
                    128: 
                    129: =over 4
                    130: 
1.89      matthew   131: =item Tables used to store meta information
                    132: 
                    133: The following tables hold data required to keep track of the current status
                    134: of a students data in the tables or to look up the students data in the tables.
                    135: 
                    136: =over 4
                    137: 
1.57      matthew   138: =item $symb_table
                    139: 
                    140: The symb_table has two columns.  The first is a 'symb_id' and the second
                    141: is the text name for the 'symb' (limited to 64k).  The 'symb_id' is generated
                    142: automatically by MySQL so inserts should be done on this table with an
                    143: empty first element.  This table has its PRIMARY KEY on the 'symb_id'.
                    144: 
                    145: =item $part_table
                    146: 
                    147: The part_table has two columns.  The first is a 'part_id' and the second
                    148: is the text name for the 'part' (limited to 100 characters).  The 'part_id' is
                    149: generated automatically by MySQL so inserts should be done on this table with
                    150: an empty first element.  This table has its PRIMARY KEY on the 'part' (100
                    151: characters) and a KEY on 'part_id'.
                    152: 
                    153: =item $student_table
                    154: 
1.113     matthew   155: The student_table has 7 columns.  The first is a 'student_id' assigned by 
                    156: MySQL.  The second is 'student' which is username:domain.  The third through
                    157: fifth are 'section', 'status' (enrollment status), and 'classification' 
                    158: (to be used in the future).  The sixth and seventh ('updatetime' and 
                    159: 'fullupdatetime') contain the time of last update and full update of student
                    160: data.  This table has its PRIMARY KEY on the 'student_id' column and is indexed
                    161: on 'student', 'section', and 'status'.
1.89      matthew   162: 
                    163: =back 
                    164: 
                    165: =item Tables used to store current status data
                    166: 
                    167: The following tables store data only about the students current status on 
                    168: a problem, meaning only the data related to the last attempt on a problem.
                    169: 
                    170: =over 4
1.57      matthew   171: 
                    172: =item $performance_table
                    173: 
                    174: The performance_table has 9 columns.  The first three are 'symb_id', 
                    175: 'student_id', and 'part_id'.  These comprise the PRIMARY KEY for this table
                    176: and are directly related to the $symb_table, $student_table, and $part_table
                    177: described above.  MySQL does better indexing on numeric items than text,
                    178: so we use these three "index tables".  The remaining columns are
                    179: 'solved', 'tries', 'awarded', 'award', 'awarddetail', and 'timestamp'.
                    180: These are either the MySQL type TINYTEXT or various integers ('tries' and 
                    181: 'timestamp').  This table has KEYs of 'student_id' and 'symb_id'.
                    182: For use of this table, see the functions described below.
                    183: 
                    184: =item $parameters_table
                    185: 
                    186: The parameters_table holds the data that does not fit neatly into the
                    187: performance_table.  The parameters table has four columns: 'symb_id',
                    188: 'student_id', 'parameter', and 'value'.  'symb_id', 'student_id', and
                    189: 'parameter' comprise the PRIMARY KEY for this table.  'parameter' is 
                    190: limited to 255 characters.  'value' is limited to 64k characters.
                    191: 
                    192: =back
                    193: 
1.89      matthew   194: =item Tables used for storing historic data
                    195: 
                    196: The following tables are used to store almost all of the transactions a student
                    197: has made on a homework problem.  See loncapa/docs/homework/datastorage for 
                    198: specific information about each of the parameters stored.  
                    199: 
                    200: =over 4
                    201: 
                    202: =item $fulldump_response_table
                    203: 
                    204: The response table holds data (documented in loncapa/docs/homework/datastorage)
                    205: associated with a particular response id which is stored when a student 
                    206: attempts a problem.  The following are the columns of the table, in order:
                    207: 'symb_id','part_id','response_id','student_id','transaction','tries',
1.93      matthew   208: 'awarddetail', 'response_specific' (data particular to the response
1.89      matthew   209: type), 'response_specific_value', and 'submission (the text of the students
                    210: submission).  The primary key is based on the first five columns listed above.
                    211: 
                    212: =item $fulldump_part_table
                    213: 
                    214: The part table holds data (documented in loncapa/docs/homework/datastorage)
                    215: associated with a particular part id which is stored when a student attempts
                    216: a problem.  The following are the columns of the table, in order:
                    217: 'symb_id','part_id','student_id','transaction','tries','award','awarded',
                    218: and 'previous'.  The primary key is based on the first five columns listed 
                    219: above.
                    220: 
                    221: =item $fulldump_timestamp_table
                    222: 
                    223: The timestamp table holds the timestamps of the transactions which are
                    224: stored in $fulldump_response_table and $fulldump_part_table.  This data is
                    225: about both the response and part data.  Columns: 'symb_id','student_id',
                    226: 'transaction', and 'timestamp'.  
                    227: The primary key is based on the first 3 columns.
                    228: 
1.127     matthew   229: =item $weight_table
                    230: 
                    231: The weight table holds the weight for the problems used in the class.
                    232: Whereas the weight of a problem can vary by section and student the data
                    233: here is applied to the class as a whole.
                    234: Columns: 'symb_id','part_id','response_id','weight'.
                    235: 
1.89      matthew   236: =back
                    237: 
                    238: =back
                    239: 
1.57      matthew   240: =head3 Important Subroutines
                    241: 
                    242: Here is a brief overview of the subroutines which are likely to be of 
                    243: interest:
                    244: 
                    245: =over 4
                    246: 
                    247: =item &get_current_state(): programmers interface.
                    248: 
                    249: =item &init_dbs(): table creation
                    250: 
                    251: =item &update_student_data(): data storage calls
                    252: 
                    253: =item &get_student_data_from_performance_cache(): data retrieval
                    254: 
                    255: =back
                    256: 
                    257: =head3 Main Documentation
                    258: 
                    259: =over 4
                    260: 
                    261: =cut
                    262: 
                    263: ################################################
                    264: ################################################
                    265: 
                    266: ################################################
                    267: ################################################
1.89      matthew   268: { # Begin scope of table identifiers
1.57      matthew   269: 
                    270: my $current_course ='';
                    271: my $symb_table;
                    272: my $part_table;
                    273: my $student_table;
                    274: my $performance_table;
                    275: my $parameters_table;
1.89      matthew   276: my $fulldump_response_table;
                    277: my $fulldump_part_table;
                    278: my $fulldump_timestamp_table;
1.127     matthew   279: my $weight_table;
1.57      matthew   280: 
1.89      matthew   281: my @Tables;
1.57      matthew   282: ################################################
                    283: ################################################
                    284: 
                    285: =pod
                    286: 
                    287: =item &init_dbs()
                    288: 
                    289: Input: course id
                    290: 
                    291: Output: 0 on success, positive integer on error
                    292: 
                    293: This routine issues the calls to lonmysql to create the tables used to
                    294: store student data.
                    295: 
                    296: =cut
                    297: 
                    298: ################################################
                    299: ################################################
                    300: sub init_dbs {
1.134     matthew   301:     my ($courseid,$drop) = @_;
1.57      matthew   302:     &setup_table_names($courseid);
                    303:     #
1.73      matthew   304:     # Drop any of the existing tables
1.134     matthew   305:     if ($drop) {
                    306:         foreach my $table (@Tables) {
                    307:             &Apache::lonmysql::drop_table($table);
                    308:         }
1.73      matthew   309:     }
                    310:     #
1.57      matthew   311:     # Note - changes to this table must be reflected in the code that 
                    312:     # stores the data (calls &Apache::lonmysql::store_row with this table
                    313:     # id
                    314:     my $symb_table_def = {
                    315:         id => $symb_table,
                    316:         permanent => 'no',
                    317:         columns => [{ name => 'symb_id',
                    318:                       type => 'MEDIUMINT UNSIGNED',
                    319:                       restrictions => 'NOT NULL',
                    320:                       auto_inc     => 'yes', },
                    321:                     { name => 'symb',
                    322:                       type => 'MEDIUMTEXT',
                    323:                       restrictions => 'NOT NULL'},
                    324:                     ],
                    325:         'PRIMARY KEY' => ['symb_id'],
                    326:     };
                    327:     #
                    328:     my $part_table_def = {
                    329:         id => $part_table,
                    330:         permanent => 'no',
                    331:         columns => [{ name => 'part_id',
                    332:                       type => 'MEDIUMINT UNSIGNED',
                    333:                       restrictions => 'NOT NULL',
                    334:                       auto_inc     => 'yes', },
                    335:                     { name => 'part',
1.132     matthew   336:                       type => 'VARCHAR(100) BINARY',
1.57      matthew   337:                       restrictions => 'NOT NULL'},
                    338:                     ],
                    339:         'PRIMARY KEY' => ['part (100)'],
                    340:         'KEY' => [{ columns => ['part_id']},],
                    341:     };
                    342:     #
                    343:     my $student_table_def = {
                    344:         id => $student_table,
                    345:         permanent => 'no',
                    346:         columns => [{ name => 'student_id',
                    347:                       type => 'MEDIUMINT UNSIGNED',
                    348:                       restrictions => 'NOT NULL',
                    349:                       auto_inc     => 'yes', },
                    350:                     { name => 'student',
1.132     matthew   351:                       type => 'VARCHAR(100) BINARY',
1.113     matthew   352:                       restrictions => 'NOT NULL UNIQUE'},
                    353:                     { name => 'section',
1.132     matthew   354:                       type => 'VARCHAR(100) BINARY',
1.113     matthew   355:                       restrictions => 'NOT NULL'},
                    356:                     { name => 'status',
1.132     matthew   357:                       type => 'VARCHAR(15) BINARY',
1.57      matthew   358:                       restrictions => 'NOT NULL'},
1.85      matthew   359:                     { name => 'classification',
1.132     matthew   360:                       type => 'VARCHAR(100) BINARY', },
1.57      matthew   361:                     { name => 'updatetime',
1.89      matthew   362:                       type => 'INT UNSIGNED'},
                    363:                     { name => 'fullupdatetime',
                    364:                       type => 'INT UNSIGNED'},
1.57      matthew   365:                     ],
1.87      matthew   366:         'PRIMARY KEY' => ['student_id'],
1.113     matthew   367:         'KEY' => [{ columns => ['student (100)',
                    368:                                 'section (100)',
                    369:                                 'status (15)',]},],
1.57      matthew   370:     };
                    371:     #
                    372:     my $performance_table_def = {
                    373:         id => $performance_table,
                    374:         permanent => 'no',
                    375:         columns => [{ name => 'symb_id',
                    376:                       type => 'MEDIUMINT UNSIGNED',
                    377:                       restrictions => 'NOT NULL'  },
                    378:                     { name => 'student_id',
                    379:                       type => 'MEDIUMINT UNSIGNED',
                    380:                       restrictions => 'NOT NULL'  },
                    381:                     { name => 'part_id',
                    382:                       type => 'MEDIUMINT UNSIGNED',
                    383:                       restrictions => 'NOT NULL' },
1.73      matthew   384:                     { name => 'part',
1.132     matthew   385:                       type => 'VARCHAR(100) BINARY',
1.73      matthew   386:                       restrictions => 'NOT NULL'},                    
1.57      matthew   387:                     { name => 'solved',
                    388:                       type => 'TINYTEXT' },
                    389:                     { name => 'tries',
                    390:                       type => 'SMALLINT UNSIGNED' },
                    391:                     { name => 'awarded',
1.127     matthew   392:                       type => 'REAL' },
1.57      matthew   393:                     { name => 'award',
                    394:                       type => 'TINYTEXT' },
                    395:                     { name => 'awarddetail',
                    396:                       type => 'TINYTEXT' },
                    397:                     { name => 'timestamp',
                    398:                       type => 'INT UNSIGNED'},
                    399:                     ],
                    400:         'PRIMARY KEY' => ['symb_id','student_id','part_id'],
                    401:         'KEY' => [{ columns=>['student_id'] },
                    402:                   { columns=>['symb_id'] },],
                    403:     };
                    404:     #
1.89      matthew   405:     my $fulldump_part_table_def = {
                    406:         id => $fulldump_part_table,
                    407:         permanent => 'no',
                    408:         columns => [
                    409:                     { name => 'symb_id',
                    410:                       type => 'MEDIUMINT UNSIGNED',
                    411:                       restrictions => 'NOT NULL'  },
                    412:                     { name => 'part_id',
                    413:                       type => 'MEDIUMINT UNSIGNED',
                    414:                       restrictions => 'NOT NULL' },
                    415:                     { name => 'student_id',
                    416:                       type => 'MEDIUMINT UNSIGNED',
                    417:                       restrictions => 'NOT NULL'  },
                    418:                     { name => 'transaction',
                    419:                       type => 'MEDIUMINT UNSIGNED',
                    420:                       restrictions => 'NOT NULL' },
                    421:                     { name => 'tries',
                    422:                       type => 'SMALLINT UNSIGNED',
                    423:                       restrictions => 'NOT NULL' },
                    424:                     { name => 'award',
                    425:                       type => 'TINYTEXT' },
                    426:                     { name => 'awarded',
1.127     matthew   427:                       type => 'REAL' },
1.89      matthew   428:                     { name => 'previous',
                    429:                       type => 'SMALLINT UNSIGNED' },
                    430: #                    { name => 'regrader',
                    431: #                      type => 'TINYTEXT' },
                    432: #                    { name => 'afterduedate',
                    433: #                      type => 'TINYTEXT' },
                    434:                     ],
                    435:         'PRIMARY KEY' => ['symb_id','part_id','student_id','transaction'],
                    436:         'KEY' => [
                    437:                   { columns=>['symb_id'] },
                    438:                   { columns=>['part_id'] },
                    439:                   { columns=>['student_id'] },
                    440:                   ],
                    441:     };
                    442:     #
                    443:     my $fulldump_response_table_def = {
                    444:         id => $fulldump_response_table,
                    445:         permanent => 'no',
                    446:         columns => [
                    447:                     { name => 'symb_id',
                    448:                       type => 'MEDIUMINT UNSIGNED',
                    449:                       restrictions => 'NOT NULL'  },
                    450:                     { name => 'part_id',
                    451:                       type => 'MEDIUMINT UNSIGNED',
                    452:                       restrictions => 'NOT NULL' },
                    453:                     { name => 'response_id',
                    454:                       type => 'MEDIUMINT UNSIGNED',
                    455:                       restrictions => 'NOT NULL'  },
                    456:                     { name => 'student_id',
                    457:                       type => 'MEDIUMINT UNSIGNED',
                    458:                       restrictions => 'NOT NULL'  },
                    459:                     { name => 'transaction',
                    460:                       type => 'MEDIUMINT UNSIGNED',
                    461:                       restrictions => 'NOT NULL' },
                    462:                     { name => 'awarddetail',
                    463:                       type => 'TINYTEXT' },
                    464: #                    { name => 'message',
1.132     matthew   465: #                      type => 'CHAR BINARY'},
1.89      matthew   466:                     { name => 'response_specific',
                    467:                       type => 'TINYTEXT' },
                    468:                     { name => 'response_specific_value',
                    469:                       type => 'TINYTEXT' },
                    470:                     { name => 'submission',
                    471:                       type => 'TEXT'},
                    472:                     ],
                    473:             'PRIMARY KEY' => ['symb_id','part_id','response_id','student_id',
                    474:                               'transaction'],
                    475:             'KEY' => [
                    476:                       { columns=>['symb_id'] },
                    477:                       { columns=>['part_id','response_id'] },
                    478:                       { columns=>['student_id'] },
                    479:                       ],
                    480:     };
                    481:     my $fulldump_timestamp_table_def = {
                    482:         id => $fulldump_timestamp_table,
                    483:         permanent => 'no',
                    484:         columns => [
                    485:                     { name => 'symb_id',
                    486:                       type => 'MEDIUMINT UNSIGNED',
                    487:                       restrictions => 'NOT NULL'  },
                    488:                     { name => 'student_id',
                    489:                       type => 'MEDIUMINT UNSIGNED',
                    490:                       restrictions => 'NOT NULL'  },
                    491:                     { name => 'transaction',
                    492:                       type => 'MEDIUMINT UNSIGNED',
                    493:                       restrictions => 'NOT NULL' },
                    494:                     { name => 'timestamp',
                    495:                       type => 'INT UNSIGNED'},
                    496:                     ],
                    497:         'PRIMARY KEY' => ['symb_id','student_id','transaction'],
                    498:         'KEY' => [
                    499:                   { columns=>['symb_id'] },
                    500:                   { columns=>['student_id'] },
                    501:                   { columns=>['transaction'] },
                    502:                   ],
                    503:     };
                    504:     #
1.57      matthew   505:     my $parameters_table_def = {
                    506:         id => $parameters_table,
                    507:         permanent => 'no',
                    508:         columns => [{ name => 'symb_id',
                    509:                       type => 'MEDIUMINT UNSIGNED',
                    510:                       restrictions => 'NOT NULL'  },
                    511:                     { name => 'student_id',
                    512:                       type => 'MEDIUMINT UNSIGNED',
                    513:                       restrictions => 'NOT NULL'  },
                    514:                     { name => 'parameter',
                    515:                       type => 'TINYTEXT',
                    516:                       restrictions => 'NOT NULL'  },
                    517:                     { name => 'value',
                    518:                       type => 'MEDIUMTEXT' },
                    519:                     ],
                    520:         'PRIMARY KEY' => ['symb_id','student_id','parameter (255)'],
                    521:     };
                    522:     #
1.127     matthew   523:     my $weight_table_def = {
                    524:         id => $weight_table,
                    525:         permanent => 'no',
                    526:         columns => [{ name => 'symb_id',
                    527:                       type => 'MEDIUMINT UNSIGNED',
                    528:                       restrictions => 'NOT NULL'  },
                    529:                     { name => 'part_id',
                    530:                       type => 'MEDIUMINT UNSIGNED',
                    531:                       restrictions => 'NOT NULL'  },
                    532:                     { name => 'weight',
                    533:                       type => 'REAL',
                    534:                       restrictions => 'NOT NULL'  },
                    535:                     ],
                    536:         'PRIMARY KEY' => ['symb_id','part_id'],
                    537:     };
                    538:     #
1.57      matthew   539:     # Create the tables
                    540:     my $tableid;
                    541:     $tableid = &Apache::lonmysql::create_table($symb_table_def);
                    542:     if (! defined($tableid)) {
                    543:         &Apache::lonnet::logthis("error creating symb_table: ".
                    544:                                  &Apache::lonmysql::get_error());
                    545:         return 1;
                    546:     }
                    547:     #
                    548:     $tableid = &Apache::lonmysql::create_table($part_table_def);
                    549:     if (! defined($tableid)) {
                    550:         &Apache::lonnet::logthis("error creating part_table: ".
                    551:                                  &Apache::lonmysql::get_error());
                    552:         return 2;
                    553:     }
                    554:     #
                    555:     $tableid = &Apache::lonmysql::create_table($student_table_def);
                    556:     if (! defined($tableid)) {
                    557:         &Apache::lonnet::logthis("error creating student_table: ".
                    558:                                  &Apache::lonmysql::get_error());
                    559:         return 3;
                    560:     }
                    561:     #
                    562:     $tableid = &Apache::lonmysql::create_table($performance_table_def);
                    563:     if (! defined($tableid)) {
                    564:         &Apache::lonnet::logthis("error creating preformance_table: ".
                    565:                                  &Apache::lonmysql::get_error());
                    566:         return 5;
                    567:     }
                    568:     #
                    569:     $tableid = &Apache::lonmysql::create_table($parameters_table_def);
                    570:     if (! defined($tableid)) {
                    571:         &Apache::lonnet::logthis("error creating parameters_table: ".
                    572:                                  &Apache::lonmysql::get_error());
                    573:         return 6;
                    574:     }
1.89      matthew   575:     #
                    576:     $tableid = &Apache::lonmysql::create_table($fulldump_part_table_def);
                    577:     if (! defined($tableid)) {
                    578:         &Apache::lonnet::logthis("error creating fulldump_part_table: ".
                    579:                                  &Apache::lonmysql::get_error());
                    580:         return 7;
                    581:     }
                    582:     #
                    583:     $tableid = &Apache::lonmysql::create_table($fulldump_response_table_def);
                    584:     if (! defined($tableid)) {
                    585:         &Apache::lonnet::logthis("error creating fulldump_response_table: ".
                    586:                                  &Apache::lonmysql::get_error());
                    587:         return 8;
                    588:     }
                    589:     $tableid = &Apache::lonmysql::create_table($fulldump_timestamp_table_def);
                    590:     if (! defined($tableid)) {
                    591:         &Apache::lonnet::logthis("error creating fulldump_timestamp_table: ".
                    592:                                  &Apache::lonmysql::get_error());
                    593:         return 9;
                    594:     }
1.127     matthew   595:     $tableid = &Apache::lonmysql::create_table($weight_table_def);
                    596:     if (! defined($tableid)) {
                    597:         &Apache::lonnet::logthis("error creating weight_table: ".
                    598:                                  &Apache::lonmysql::get_error());
                    599:         return 10;
                    600:     }
1.57      matthew   601:     return 0;
1.70      matthew   602: }
                    603: 
                    604: ################################################
                    605: ################################################
                    606: 
                    607: =pod
                    608: 
                    609: =item &delete_caches()
                    610: 
1.144     matthew   611: This routine drops all the tables associated with a course from the 
                    612: MySQL database.
                    613: 
                    614: Input: course id (optional, determined by environment if omitted) 
                    615: 
                    616: Returns: nothing
                    617: 
1.70      matthew   618: =cut
                    619: 
                    620: ################################################
                    621: ################################################
                    622: sub delete_caches {
                    623:     my $courseid = shift;
1.146     albertel  624:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.70      matthew   625:     #
                    626:     &setup_table_names($courseid);
                    627:     #
                    628:     my $dbh = &Apache::lonmysql::get_dbh();
1.89      matthew   629:     foreach my $table (@Tables) {
1.70      matthew   630:         my $command = 'DROP TABLE '.$table.';';
                    631:         $dbh->do($command);
                    632:         if ($dbh->err) {
                    633:             &Apache::lonnet::logthis($command.' resulted in error: '.$dbh->errstr);
                    634:         }
                    635:     }
                    636:     return;
1.57      matthew   637: }
                    638: 
                    639: ################################################
                    640: ################################################
                    641: 
                    642: =pod
                    643: 
                    644: =item &get_part_id()
                    645: 
                    646: Get the MySQL id of a problem part string.
                    647: 
                    648: Input: $part
                    649: 
                    650: Output: undef on error, integer $part_id on success.
                    651: 
                    652: =item &get_part()
                    653: 
                    654: Get the string describing a part from the MySQL id of the problem part.
                    655: 
                    656: Input: $part_id
                    657: 
                    658: Output: undef on error, $part string on success.
                    659: 
                    660: =cut
                    661: 
                    662: ################################################
                    663: ################################################
                    664: 
1.61      matthew   665: my $have_read_part_table = 0;
1.57      matthew   666: my %ids_by_part;
                    667: my %parts_by_id;
                    668: 
                    669: sub get_part_id {
                    670:     my ($part) = @_;
1.61      matthew   671:     $part = 0 if (! defined($part));
                    672:     if (! $have_read_part_table) {
                    673:         my @Result = &Apache::lonmysql::get_rows($part_table);
                    674:         foreach (@Result) {
                    675:             $ids_by_part{$_->[1]}=$_->[0];
                    676:         }
                    677:         $have_read_part_table = 1;
                    678:     }
1.57      matthew   679:     if (! exists($ids_by_part{$part})) {
                    680:         &Apache::lonmysql::store_row($part_table,[undef,$part]);
                    681:         undef(%ids_by_part);
                    682:         my @Result = &Apache::lonmysql::get_rows($part_table);
                    683:         foreach (@Result) {
                    684:             $ids_by_part{$_->[1]}=$_->[0];
                    685:         }
                    686:     }
                    687:     return $ids_by_part{$part} if (exists($ids_by_part{$part}));
                    688:     return undef; # error
                    689: }
                    690: 
                    691: sub get_part {
                    692:     my ($part_id) = @_;
                    693:     if (! exists($parts_by_id{$part_id})  || 
                    694:         ! defined($parts_by_id{$part_id}) ||
                    695:         $parts_by_id{$part_id} eq '') {
                    696:         my @Result = &Apache::lonmysql::get_rows($part_table);
                    697:         foreach (@Result) {
                    698:             $parts_by_id{$_->[0]}=$_->[1];
                    699:         }
                    700:     }
                    701:     return $parts_by_id{$part_id} if(exists($parts_by_id{$part_id}));
                    702:     return undef; # error
                    703: }
                    704: 
                    705: ################################################
                    706: ################################################
                    707: 
                    708: =pod
                    709: 
                    710: =item &get_symb_id()
                    711: 
                    712: Get the MySQL id of a symb.
                    713: 
                    714: Input: $symb
                    715: 
                    716: Output: undef on error, integer $symb_id on success.
                    717: 
                    718: =item &get_symb()
                    719: 
                    720: Get the symb associated with a MySQL symb_id.
                    721: 
                    722: Input: $symb_id
                    723: 
                    724: Output: undef on error, $symb on success.
                    725: 
                    726: =cut
                    727: 
                    728: ################################################
                    729: ################################################
                    730: 
1.61      matthew   731: my $have_read_symb_table = 0;
1.57      matthew   732: my %ids_by_symb;
                    733: my %symbs_by_id;
                    734: 
                    735: sub get_symb_id {
                    736:     my ($symb) = @_;
1.61      matthew   737:     if (! $have_read_symb_table) {
                    738:         my @Result = &Apache::lonmysql::get_rows($symb_table);
                    739:         foreach (@Result) {
                    740:             $ids_by_symb{$_->[1]}=$_->[0];
                    741:         }
                    742:         $have_read_symb_table = 1;
                    743:     }
1.57      matthew   744:     if (! exists($ids_by_symb{$symb})) {
                    745:         &Apache::lonmysql::store_row($symb_table,[undef,$symb]);
                    746:         undef(%ids_by_symb);
                    747:         my @Result = &Apache::lonmysql::get_rows($symb_table);
                    748:         foreach (@Result) {
                    749:             $ids_by_symb{$_->[1]}=$_->[0];
                    750:         }
                    751:     }
                    752:     return $ids_by_symb{$symb} if(exists( $ids_by_symb{$symb}));
                    753:     return undef; # error
                    754: }
                    755: 
                    756: sub get_symb {
                    757:     my ($symb_id) = @_;
                    758:     if (! exists($symbs_by_id{$symb_id})  || 
                    759:         ! defined($symbs_by_id{$symb_id}) ||
                    760:         $symbs_by_id{$symb_id} eq '') {
                    761:         my @Result = &Apache::lonmysql::get_rows($symb_table);
                    762:         foreach (@Result) {
                    763:             $symbs_by_id{$_->[0]}=$_->[1];
                    764:         }
                    765:     }
                    766:     return $symbs_by_id{$symb_id} if(exists( $symbs_by_id{$symb_id}));
                    767:     return undef; # error
                    768: }
                    769: 
                    770: ################################################
                    771: ################################################
                    772: 
                    773: =pod
                    774: 
                    775: =item &get_student_id()
                    776: 
                    777: Get the MySQL id of a student.
                    778: 
                    779: Input: $sname, $dom
                    780: 
                    781: Output: undef on error, integer $student_id on success.
                    782: 
                    783: =item &get_student()
                    784: 
                    785: Get student username:domain associated with the MySQL student_id.
                    786: 
                    787: Input: $student_id
                    788: 
                    789: Output: undef on error, string $student (username:domain) on success.
                    790: 
                    791: =cut
                    792: 
                    793: ################################################
                    794: ################################################
                    795: 
1.61      matthew   796: my $have_read_student_table = 0;
1.57      matthew   797: my %ids_by_student;
                    798: my %students_by_id;
                    799: 
                    800: sub get_student_id {
                    801:     my ($sname,$sdom) = @_;
                    802:     my $student = $sname.':'.$sdom;
1.61      matthew   803:     if (! $have_read_student_table) {
                    804:         my @Result = &Apache::lonmysql::get_rows($student_table);
                    805:         foreach (@Result) {
                    806:             $ids_by_student{$_->[1]}=$_->[0];
                    807:         }
                    808:         $have_read_student_table = 1;
                    809:     }
1.57      matthew   810:     if (! exists($ids_by_student{$student})) {
1.113     matthew   811:         &populate_student_table();
1.57      matthew   812:         undef(%ids_by_student);
1.113     matthew   813:         undef(%students_by_id);
1.57      matthew   814:         my @Result = &Apache::lonmysql::get_rows($student_table);
                    815:         foreach (@Result) {
                    816:             $ids_by_student{$_->[1]}=$_->[0];
                    817:         }
                    818:     }
                    819:     return $ids_by_student{$student} if(exists( $ids_by_student{$student}));
                    820:     return undef; # error
                    821: }
                    822: 
                    823: sub get_student {
                    824:     my ($student_id) = @_;
                    825:     if (! exists($students_by_id{$student_id})  || 
                    826:         ! defined($students_by_id{$student_id}) ||
                    827:         $students_by_id{$student_id} eq '') {
                    828:         my @Result = &Apache::lonmysql::get_rows($student_table);
                    829:         foreach (@Result) {
                    830:             $students_by_id{$_->[0]}=$_->[1];
                    831:         }
                    832:     }
                    833:     return $students_by_id{$student_id} if(exists($students_by_id{$student_id}));
                    834:     return undef; # error
                    835: }
1.99      matthew   836: 
1.113     matthew   837: sub populate_student_table {
                    838:     my ($courseid) = @_;
                    839:     if (! defined($courseid)) {
1.146     albertel  840:         $courseid = $env{'request.course.id'};
1.113     matthew   841:     }
                    842:     #
                    843:     &setup_table_names($courseid);
1.134     matthew   844:     &init_dbs($courseid,0);
1.113     matthew   845:     my $dbh = &Apache::lonmysql::get_dbh();
                    846:     my $request = 'INSERT IGNORE INTO '.$student_table.
                    847:         "(student,section,status) VALUES ";
1.150     albertel  848:     my $cdom = $env{'course.'.$courseid.'.domain'};
                    849:     my $cnum = $env{'course.'.$courseid.'.num'};
                    850:     my $classlist = &get_classlist($cdom,$cnum);
1.113     matthew   851:     my $student_count=0;
                    852:     while (my ($student,$data) = each %$classlist) {
                    853:         my ($section,$status) = ($data->[&CL_SECTION()],
                    854:                                  $data->[&CL_STATUS()]);
                    855:         if ($section eq '' || $section =~ /^\s*$/) {
                    856:             $section = 'none';
                    857:         }
                    858:         $request .= "('".$student."','".$section."','".$status."'),";
                    859:         $student_count++;
                    860:     }
                    861:     return if ($student_count == 0);
                    862:     chop($request);
                    863:     $dbh->do($request);
                    864:     if ($dbh->err()) {
                    865:         &Apache::lonnet::logthis("error ".$dbh->errstr().
                    866:                                  " occured executing \n".
                    867:                                  $request);
                    868:     }
                    869:     return;
                    870: }
                    871: 
1.99      matthew   872: ################################################
                    873: ################################################
                    874: 
                    875: =pod
                    876: 
                    877: =item &clear_internal_caches()
                    878: 
                    879: Causes the internal caches used in get_student_id, get_student,
                    880: get_symb_id, get_symb, get_part_id, and get_part to be undef'd.
                    881: 
                    882: Needs to be called before the first operation with the MySQL database
                    883: for a given Apache request.
                    884: 
                    885: =cut
                    886: 
                    887: ################################################
                    888: ################################################
                    889: sub clear_internal_caches {
                    890:     $have_read_part_table = 0;
                    891:     undef(%ids_by_part);
                    892:     undef(%parts_by_id);
                    893:     $have_read_symb_table = 0;
                    894:     undef(%ids_by_symb);
                    895:     undef(%symbs_by_id);
                    896:     $have_read_student_table = 0;
                    897:     undef(%ids_by_student);
                    898:     undef(%students_by_id);
                    899: }
                    900: 
1.57      matthew   901: ################################################
                    902: ################################################
                    903: 
                    904: =pod
                    905: 
1.89      matthew   906: =item &update_full_student_data($sname,$sdom,$courseid)
                    907: 
                    908: Does a lonnet::dump on a student to populate the courses tables.
                    909: 
                    910: Input: $sname, $sdom, $courseid
                    911: 
                    912: Output: $returnstatus
                    913: 
                    914: $returnstatus is a string describing any errors that occured.  'okay' is the
                    915: default.
                    916: 
                    917: This subroutine loads a students data using lonnet::dump and inserts
                    918: it into the MySQL database.  The inserts are done on three tables, 
                    919: $fulldump_response_table, $fulldump_part_table, and $fulldump_timestamp_table.
                    920: The INSERT calls are made directly by this subroutine, not through lonmysql 
                    921: because we do a 'bulk'insert which takes advantage of MySQLs non-SQL 
                    922: compliant INSERT command to insert multiple rows at a time.  
                    923: If anything has gone wrong during this process, $returnstatus is updated with 
                    924: a description of the error.
                    925: 
                    926: Once the "fulldump" tables are updated, the tables used for chart and
                    927: spreadsheet (which hold only the current state of the student on their
                    928: homework, not historical data) are updated.  If all updates have occured 
1.113     matthew   929: successfully, $student_table is updated to reflect the time of the update.
1.89      matthew   930: 
                    931: Notice we do not insert the data and immediately query it.  This means it
                    932: is possible for there to be data returned this first time that is not 
                    933: available the second time.  CYA.
                    934: 
                    935: =cut
                    936: 
                    937: ################################################
                    938: ################################################
                    939: sub update_full_student_data {
                    940:     my ($sname,$sdom,$courseid) = @_;
                    941:     #
                    942:     # Set up database names
                    943:     &setup_table_names($courseid);
                    944:     #
                    945:     my $student_id = &get_student_id($sname,$sdom);
                    946:     my $student = $sname.':'.$sdom;
                    947:     #
                    948:     my $returnstatus = 'okay';
                    949:     #
                    950:     # Download students data
                    951:     my $time_of_retrieval = time;
                    952:     my @tmp = &Apache::lonnet::dump($courseid,$sdom,$sname);
                    953:     if (@tmp && $tmp[0] =~ /^error/) {
                    954:         $returnstatus = 'error retrieving full student data';
                    955:         return $returnstatus;
                    956:     } elsif (! @tmp) {
                    957:         $returnstatus = 'okay: no student data';
                    958:         return $returnstatus;
                    959:     }
                    960:     my %studentdata = @tmp;
                    961:     #
                    962:     # Get database handle and clean out the tables 
                    963:     my $dbh = &Apache::lonmysql::get_dbh();
                    964:     $dbh->do('DELETE FROM '.$fulldump_response_table.' WHERE student_id='.
                    965:              $student_id);
                    966:     $dbh->do('DELETE FROM '.$fulldump_part_table.' WHERE student_id='.
                    967:              $student_id);
                    968:     $dbh->do('DELETE FROM '.$fulldump_timestamp_table.' WHERE student_id='.
                    969:              $student_id);
                    970:     #
                    971:     # Parse and store the data into a form we can handle
                    972:     my $partdata;
                    973:     my $respdata;
                    974:     while (my ($key,$value) = each(%studentdata)) {
                    975:         next if ($key =~ /^(\d+):(resource$|subnum$|keys:)/);
                    976:         my ($transaction,$symb,$parameter) = split(':',$key);
                    977:         my $symb_id = &get_symb_id($symb);
                    978:         if ($parameter eq 'timestamp') {
                    979:             # We can deal with 'timestamp' right away
                    980:             my @timestamp_storage = ($symb_id,$student_id,
                    981:                                      $transaction,$value);
1.98      matthew   982:             my $store_command = 'INSERT IGNORE INTO '.$fulldump_timestamp_table.
1.89      matthew   983:                 " VALUES ('".join("','",@timestamp_storage)."');";
                    984:             $dbh->do($store_command);
                    985:             if ($dbh->err()) {
                    986:                 &Apache::lonnet::logthis('unable to execute '.$store_command);
                    987:                 &Apache::lonnet::logthis($dbh->errstr());
                    988:             }
                    989:             next;
                    990:         } elsif ($parameter eq 'version') {
                    991:             next;
1.90      matthew   992:         } elsif ($parameter =~ /^resource\.(.*)\.(tries|
                    993:                                                   award|
                    994:                                                   awarded|
                    995:                                                   previous|
                    996:                                                   solved|
                    997:                                                   awarddetail|
                    998:                                                   submission|
                    999:                                                   submissiongrading|
                   1000:                                                   molecule)\s*$/x){
1.89      matthew  1001:             # we do not have enough information to store an 
                   1002:             # entire row, so we save it up until later.
                   1003:             my ($part_and_resp_id,$field) = ($1,$2);
                   1004:             my ($part,$part_id,$resp,$resp_id);
                   1005:             if ($part_and_resp_id =~ /\./) {
                   1006:                 ($part,$resp) = split(/\./,$part_and_resp_id);
                   1007:                 $part_id = &get_part_id($part);
                   1008:                 $resp_id = &get_part_id($resp);
                   1009:             } else {
                   1010:                 $part_id = &get_part_id($part_and_resp_id);
                   1011:             }
1.90      matthew  1012:             # Deal with part specific data
1.89      matthew  1013:             if ($field =~ /^(tries|award|awarded|previous)$/) {
                   1014:                 $partdata->{$symb_id}->{$part_id}->{$transaction}->{$field}=$value;
                   1015:             }
1.90      matthew  1016:             # deal with response specific data
1.89      matthew  1017:             if (defined($resp_id) &&
1.100     matthew  1018:                 $field =~ /^(awarddetail|
1.90      matthew  1019:                              submission|
                   1020:                              submissiongrading|
                   1021:                              molecule)$/x) {
1.89      matthew  1022:                 if ($field eq 'submission') {
                   1023:                     # We have to be careful with user supplied input.
                   1024:                     # most of the time we are okay because it is escaped.
                   1025:                     # However, there is one wrinkle: submissions which end in
                   1026:                     # and odd number of '\' cause insert errors to occur.  
                   1027:                     # Best trap this somehow...
1.116     matthew  1028:                     $value = $dbh->quote($value);
1.89      matthew  1029:                 }
1.90      matthew  1030:                 if ($field eq 'submissiongrading' || 
                   1031:                     $field eq 'molecule') {
                   1032:                     $respdata->{$symb_id}->{$part_id}->{$resp_id}->{$transaction}->{'response_specific'}=$field;
                   1033:                     $respdata->{$symb_id}->{$part_id}->{$resp_id}->{$transaction}->{'response_specific_value'}=$value;
                   1034:                 } else {
                   1035:                     $respdata->{$symb_id}->{$part_id}->{$resp_id}->{$transaction}->{$field}=$value;
                   1036:                 }
1.89      matthew  1037:             }
                   1038:         }
                   1039:     }
                   1040:     ##
                   1041:     ## Store the part data
1.98      matthew  1042:     my $store_command = 'INSERT IGNORE INTO '.$fulldump_part_table.
1.89      matthew  1043:         ' VALUES '."\n";
                   1044:     my $store_rows = 0;
                   1045:     while (my ($symb_id,$hash1) = each (%$partdata)) {
                   1046:         while (my ($part_id,$hash2) = each (%$hash1)) {
                   1047:             while (my ($transaction,$data) = each (%$hash2)) {
                   1048:                 $store_command .= "('".join("','",$symb_id,$part_id,
                   1049:                                             $student_id,
                   1050:                                             $transaction,
1.101     matthew  1051:                                             $data->{'tries'},
1.89      matthew  1052:                                             $data->{'award'},
                   1053:                                             $data->{'awarded'},
                   1054:                                             $data->{'previous'})."'),";
                   1055:                 $store_rows++;
                   1056:             }
                   1057:         }
                   1058:     }
                   1059:     if ($store_rows) {
                   1060:         chop($store_command);
                   1061:         $dbh->do($store_command);
                   1062:         if ($dbh->err) {
                   1063:             $returnstatus = 'error storing part data';
                   1064:             &Apache::lonnet::logthis('insert error '.$dbh->errstr());
                   1065:             &Apache::lonnet::logthis("While attempting\n".$store_command);
                   1066:         }
                   1067:     }
                   1068:     ##
                   1069:     ## Store the response data
1.98      matthew  1070:     $store_command = 'INSERT IGNORE INTO '.$fulldump_response_table.
1.89      matthew  1071:         ' VALUES '."\n";
                   1072:     $store_rows = 0;
                   1073:     while (my ($symb_id,$hash1) = each (%$respdata)) {
                   1074:         while (my ($part_id,$hash2) = each (%$hash1)) {
                   1075:             while (my ($resp_id,$hash3) = each (%$hash2)) {
                   1076:                 while (my ($transaction,$data) = each (%$hash3)) {
1.112     matthew  1077:                     my $submission = $data->{'submission'};
                   1078:                     # We have to be careful with user supplied input.
                   1079:                     # most of the time we are okay because it is escaped.
                   1080:                     # However, there is one wrinkle: submissions which end in
                   1081:                     # and odd number of '\' cause insert errors to occur.  
                   1082:                     # Best trap this somehow...
                   1083:                     $submission = $dbh->quote($submission);
                   1084:                     $store_command .= "('".
                   1085:                         join("','",$symb_id,$part_id,
                   1086:                              $resp_id,$student_id,
                   1087:                              $transaction,
                   1088:                              $data->{'awarddetail'},
                   1089:                              $data->{'response_specific'},
                   1090:                              $data->{'response_specific_value'}).
                   1091:                              "',".$submission."),";
1.89      matthew  1092:                     $store_rows++;
                   1093:                 }
                   1094:             }
                   1095:         }
                   1096:     }
                   1097:     if ($store_rows) {
                   1098:         chop($store_command);
                   1099:         $dbh->do($store_command);
                   1100:         if ($dbh->err) {
                   1101:             $returnstatus = 'error storing response data';
                   1102:             &Apache::lonnet::logthis('insert error '.$dbh->errstr());
                   1103:             &Apache::lonnet::logthis("While attempting\n".$store_command);
                   1104:         }
                   1105:     }
                   1106:     ##
                   1107:     ## Update the students "current" data in the performance 
                   1108:     ## and parameters tables.
                   1109:     my ($status,undef) = &store_student_data
                   1110:         ($sname,$sdom,$courseid,
                   1111:          &Apache::lonnet::convert_dump_to_currentdump(\%studentdata));
                   1112:     if ($returnstatus eq 'okay' && $status ne 'okay') {
                   1113:         $returnstatus = 'error storing current data:'.$status;
                   1114:     } elsif ($status ne 'okay') {
                   1115:         $returnstatus .= ' error storing current data:'.$status;
                   1116:     }        
                   1117:     ##
                   1118:     ## Update the students time......
                   1119:     if ($returnstatus eq 'okay') {
1.113     matthew  1120:         &store_updatetime($student_id,$time_of_retrieval,$time_of_retrieval);
                   1121:         if ($dbh->err) {
                   1122:             if ($returnstatus eq 'okay') {
                   1123:                 $returnstatus = 'error updating student time';
                   1124:             } else {
                   1125:                 $returnstatus = 'error updating student time';
                   1126:             }
                   1127:         }
1.89      matthew  1128:     }
                   1129:     return $returnstatus;
                   1130: }
                   1131: 
                   1132: ################################################
                   1133: ################################################
                   1134: 
                   1135: =pod
                   1136: 
1.57      matthew  1137: =item &update_student_data()
                   1138: 
                   1139: Input: $sname, $sdom, $courseid
                   1140: 
                   1141: Output: $returnstatus, \%student_data
                   1142: 
                   1143: $returnstatus is a string describing any errors that occured.  'okay' is the
                   1144: default.
                   1145: \%student_data is the data returned by a call to lonnet::currentdump.
                   1146: 
                   1147: This subroutine loads a students data using lonnet::currentdump and inserts
                   1148: it into the MySQL database.  The inserts are done on two tables, 
                   1149: $performance_table and $parameters_table.  $parameters_table holds the data 
                   1150: that is not included in $performance_table.  See the description of 
                   1151: $performance_table elsewhere in this file.  The INSERT calls are made
                   1152: directly by this subroutine, not through lonmysql because we do a 'bulk'
                   1153: insert which takes advantage of MySQLs non-SQL compliant INSERT command to 
                   1154: insert multiple rows at a time.  If anything has gone wrong during this
                   1155: process, $returnstatus is updated with a description of the error and
                   1156: \%student_data is returned.  
                   1157: 
                   1158: Notice we do not insert the data and immediately query it.  This means it
                   1159: is possible for there to be data returned this first time that is not 
                   1160: available the second time.  CYA.
                   1161: 
                   1162: =cut
                   1163: 
                   1164: ################################################
                   1165: ################################################
                   1166: sub update_student_data {
                   1167:     my ($sname,$sdom,$courseid) = @_;
                   1168:     #
1.60      matthew  1169:     # Set up database names
                   1170:     &setup_table_names($courseid);
                   1171:     #
1.57      matthew  1172:     my $student_id = &get_student_id($sname,$sdom);
                   1173:     my $student = $sname.':'.$sdom;
                   1174:     #
                   1175:     my $returnstatus = 'okay';
                   1176:     #
                   1177:     # Download students data
                   1178:     my $time_of_retrieval = time;
                   1179:     my @tmp = &Apache::lonnet::currentdump($courseid,$sdom,$sname);
                   1180:     if ((scalar(@tmp) > 0) && ($tmp[0] =~ /^error:/)) {
                   1181:         &Apache::lonnet::logthis('error getting data for '.
                   1182:                                  $sname.':'.$sdom.' in course '.$courseid.
                   1183:                                  ':'.$tmp[0]);
                   1184:         $returnstatus = 'error getting data';
1.79      matthew  1185:         return ($returnstatus,undef);
1.57      matthew  1186:     }
                   1187:     if (scalar(@tmp) < 1) {
                   1188:         return ('no data',undef);
                   1189:     }
                   1190:     my %student_data = @tmp;
1.89      matthew  1191:     my @Results = &store_student_data($sname,$sdom,$courseid,\%student_data);
                   1192:     #
                   1193:     # Set the students update time
1.96      matthew  1194:     if ($Results[0] eq 'okay') {
1.148     matthew  1195:         &store_updatetime($student_id,$time_of_retrieval);
1.95      matthew  1196:     }
1.89      matthew  1197:     #
                   1198:     return @Results;
                   1199: }
                   1200: 
1.113     matthew  1201: sub store_updatetime {
                   1202:     my ($student_id,$updatetime,$fullupdatetime)=@_;
                   1203:     my $values = '';
                   1204:     if (defined($updatetime)) {
                   1205:         $values = 'updatetime='.$updatetime.' ';
                   1206:     }
                   1207:     if (defined($fullupdatetime)) {
                   1208:         if ($values ne '') {
                   1209:             $values .= ',';
                   1210:         }
                   1211:         $values .= 'fullupdatetime='.$fullupdatetime.' ';
                   1212:     }
                   1213:     return if ($values eq '');
                   1214:     my $dbh = &Apache::lonmysql::get_dbh();
                   1215:     my $request = 'UPDATE '.$student_table.' SET '.$values.
                   1216:         ' WHERE student_id='.$student_id.' LIMIT 1';
                   1217:     $dbh->do($request);
                   1218: }
                   1219: 
1.89      matthew  1220: sub store_student_data {
                   1221:     my ($sname,$sdom,$courseid,$student_data) = @_;
                   1222:     #
                   1223:     my $student_id = &get_student_id($sname,$sdom);
                   1224:     my $student = $sname.':'.$sdom;
                   1225:     #
                   1226:     my $returnstatus = 'okay';
1.57      matthew  1227:     #
                   1228:     # Remove all of the students data from the table
1.60      matthew  1229:     my $dbh = &Apache::lonmysql::get_dbh();
                   1230:     $dbh->do('DELETE FROM '.$performance_table.' WHERE student_id='.
                   1231:              $student_id);
                   1232:     $dbh->do('DELETE FROM '.$parameters_table.' WHERE student_id='.
                   1233:              $student_id);
1.57      matthew  1234:     #
                   1235:     # Store away the data
                   1236:     #
                   1237:     my $starttime = Time::HiRes::time;
                   1238:     my $elapsed = 0;
                   1239:     my $rows_stored;
1.98      matthew  1240:     my $store_parameters_command  = 'INSERT IGNORE INTO '.$parameters_table.
1.60      matthew  1241:         ' VALUES '."\n";
1.61      matthew  1242:     my $num_parameters = 0;
1.98      matthew  1243:     my $store_performance_command = 'INSERT IGNORE INTO '.$performance_table.
1.60      matthew  1244:         ' VALUES '."\n";
1.79      matthew  1245:     return ('error',undef) if (! defined($dbh));
1.89      matthew  1246:     while (my ($current_symb,$param_hash) = each(%{$student_data})) {
1.57      matthew  1247:         #
                   1248:         # make sure the symb is set up properly
                   1249:         my $symb_id = &get_symb_id($current_symb);
                   1250:         #
1.147     matthew  1251:         # Parameters
1.63      matthew  1252:         while (my ($parameter,$value) = each(%$param_hash)) {
                   1253:             if ($parameter !~ /(timestamp|resource\.(.*)\.(solved|tries|awarded|award|awarddetail|previous))/) {
1.147     matthew  1254:                 my $sql_parameter = "('".join("','",
                   1255:                                               $symb_id,$student_id,
                   1256:                                               $parameter)."',".
                   1257:                                                   $dbh->quote($value)."),\n";
1.61      matthew  1258:                 $num_parameters ++;
1.147     matthew  1259:                 if ($sql_parameter !~ /''/) {
                   1260:                     $store_parameters_command .= $sql_parameter;
1.149     albertel 1261:                     #$rows_stored++;
1.57      matthew  1262:                 }
                   1263:             }
1.147     matthew  1264:         }
                   1265:         # Performance
                   1266:         my %stored;
                   1267:         while (my ($parameter,$value) = each(%$param_hash)) {
                   1268:             next if ($parameter !~ /^resource\.(.*)\.(solved|awarded)$/);
                   1269:             my $part = $1;
1.151     albertel 1270: 	    next if ($part =~ /\./);
1.147     matthew  1271:             next if (exists($stored{$part}));
                   1272:             $stored{$part}++;
1.57      matthew  1273:             #
                   1274:             my $part_id = &get_part_id($part);
                   1275:             next if (!defined($part_id));
                   1276:             my $solved  = $value;
                   1277:             my $tries   = $param_hash->{'resource.'.$part.'.tries'};
                   1278:             my $awarded = $param_hash->{'resource.'.$part.'.awarded'};
                   1279:             my $award   = $param_hash->{'resource.'.$part.'.award'};
                   1280:             my $awarddetail = $param_hash->{'resource.'.$part.'.awarddetail'};
                   1281:             my $timestamp = $param_hash->{'timestamp'};
1.60      matthew  1282:             #
1.74      matthew  1283:             $solved      = '' if (! defined($solved));
1.57      matthew  1284:             $tries       = '' if (! defined($tries));
                   1285:             $awarded     = '' if (! defined($awarded));
                   1286:             $award       = '' if (! defined($award));
                   1287:             $awarddetail = '' if (! defined($awarddetail));
1.147     matthew  1288:             my $sql_performance = 
                   1289:                 "('".join("','",$symb_id,$student_id,$part_id,$part,
                   1290:                                 $solved,$tries,$awarded,$award,
                   1291:                                 $awarddetail,$timestamp)."'),\n";
                   1292:             $store_performance_command .= $sql_performance;
1.57      matthew  1293:             $rows_stored++;
                   1294:         }
                   1295:     }
1.149     albertel 1296:     if (! $rows_stored) { return ($returnstatus, undef); }
1.147     matthew  1297:     $store_parameters_command =~ s|,\n$||;
                   1298:     $store_performance_command =~ s|,\n$||;
1.57      matthew  1299:     my $start = Time::HiRes::time;
1.94      matthew  1300:     $dbh->do($store_performance_command);
                   1301:     if ($dbh->err()) {
1.147     matthew  1302:         &Apache::lonnet::logthis('performance bigass insert error:'.
                   1303:                                  $dbh->errstr());
                   1304:         &Apache::lonnet::logthis('command = '.$/.$store_performance_command);
1.94      matthew  1305:         $returnstatus = 'error: unable to insert performance into database';
                   1306:         return ($returnstatus,$student_data);
                   1307:     }
1.61      matthew  1308:     $dbh->do($store_parameters_command) if ($num_parameters>0);
1.57      matthew  1309:     if ($dbh->err()) {
1.147     matthew  1310:         &Apache::lonnet::logthis('parameters bigass insert error:'.
                   1311:                                  $dbh->errstr());
                   1312:         &Apache::lonnet::logthis('command = '.$/.$store_parameters_command);
1.87      matthew  1313:         &Apache::lonnet::logthis('rows_stored = '.$rows_stored);
                   1314:         &Apache::lonnet::logthis('student_id = '.$student_id);
1.57      matthew  1315:         $returnstatus = 'error: unable to insert parameters into database';
1.89      matthew  1316:         return ($returnstatus,$student_data);
1.57      matthew  1317:     }
                   1318:     $elapsed += Time::HiRes::time - $start;
1.89      matthew  1319:     return ($returnstatus,$student_data);
1.57      matthew  1320: }
                   1321: 
1.89      matthew  1322: ######################################
                   1323: ######################################
1.57      matthew  1324: 
                   1325: =pod
                   1326: 
1.89      matthew  1327: =item &ensure_tables_are_set_up($courseid)
1.57      matthew  1328: 
1.89      matthew  1329: Checks to be sure the MySQL tables for the given class are set up.
                   1330: If $courseid is omitted it will be obtained from the environment.
1.57      matthew  1331: 
1.89      matthew  1332: Returns nothing on success and 'error' on failure
1.57      matthew  1333: 
                   1334: =cut
                   1335: 
1.89      matthew  1336: ######################################
                   1337: ######################################
                   1338: sub ensure_tables_are_set_up {
                   1339:     my ($courseid) = @_;
1.146     albertel 1340:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.61      matthew  1341:     # 
                   1342:     # Clean out package variables
1.57      matthew  1343:     &setup_table_names($courseid);
                   1344:     #
                   1345:     # if the tables do not exist, make them
                   1346:     my @CurrentTable = &Apache::lonmysql::tables_in_db();
1.113     matthew  1347:     my ($found_symb,$found_student,$found_part,
1.89      matthew  1348:         $found_performance,$found_parameters,$found_fulldump_part,
1.127     matthew  1349:         $found_fulldump_response,$found_fulldump_timestamp,
                   1350:         $found_weight);
1.57      matthew  1351:     foreach (@CurrentTable) {
                   1352:         $found_symb        = 1 if ($_ eq $symb_table);
                   1353:         $found_student     = 1 if ($_ eq $student_table);
                   1354:         $found_part        = 1 if ($_ eq $part_table);
                   1355:         $found_performance = 1 if ($_ eq $performance_table);
                   1356:         $found_parameters  = 1 if ($_ eq $parameters_table);
1.89      matthew  1357:         $found_fulldump_part      = 1 if ($_ eq $fulldump_part_table);
                   1358:         $found_fulldump_response  = 1 if ($_ eq $fulldump_response_table);
                   1359:         $found_fulldump_timestamp = 1 if ($_ eq $fulldump_timestamp_table);
1.127     matthew  1360:         $found_weight      = 1 if ($_ eq $weight_table);
1.57      matthew  1361:     }
1.127     matthew  1362:     if (!$found_symb          || 
                   1363:         !$found_student       || !$found_part              ||
                   1364:         !$found_performance   || !$found_parameters        ||
1.89      matthew  1365:         !$found_fulldump_part || !$found_fulldump_response ||
1.127     matthew  1366:         !$found_fulldump_timestamp || !$found_weight ) {
1.134     matthew  1367:         if (&init_dbs($courseid,1)) {
1.89      matthew  1368:             return 'error';
1.57      matthew  1369:         }
                   1370:     }
1.89      matthew  1371: }
                   1372: 
                   1373: ################################################
                   1374: ################################################
                   1375: 
                   1376: =pod
                   1377: 
                   1378: =item &ensure_current_data()
                   1379: 
                   1380: Input: $sname, $sdom, $courseid
                   1381: 
                   1382: Output: $status, $data
                   1383: 
                   1384: This routine ensures the data for a given student is up to date.
1.113     matthew  1385: The $student_table is queried to determine the time of the last update.  
1.89      matthew  1386: If the students data is out of date, &update_student_data() is called.  
                   1387: The return values from the call to &update_student_data() are returned.
                   1388: 
                   1389: =cut
                   1390: 
                   1391: ################################################
                   1392: ################################################
                   1393: sub ensure_current_data {
                   1394:     my ($sname,$sdom,$courseid) = @_;
                   1395:     my $status = 'okay';   # return value
                   1396:     #
1.146     albertel 1397:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.89      matthew  1398:     &ensure_tables_are_set_up($courseid);
1.57      matthew  1399:     #
                   1400:     # Get the update time for the user
                   1401:     my $updatetime = 0;
1.60      matthew  1402:     my $modifiedtime = &Apache::lonnet::GetFileTimestamp
                   1403:         ($sdom,$sname,$courseid.'.db',
                   1404:          $Apache::lonnet::perlvar{'lonUsersDir'});
1.57      matthew  1405:     #
1.87      matthew  1406:     my $student_id = &get_student_id($sname,$sdom);
1.113     matthew  1407:     my @Result = &Apache::lonmysql::get_rows($student_table,
1.87      matthew  1408:                                              "student_id ='$student_id'");
1.57      matthew  1409:     my $data = undef;
                   1410:     if (@Result) {
1.113     matthew  1411:         $updatetime = $Result[0]->[5];  # Ack!  This is dumb!
1.57      matthew  1412:     }
                   1413:     if ($modifiedtime > $updatetime) {
                   1414:         ($status,$data) = &update_student_data($sname,$sdom,$courseid);
                   1415:     }
                   1416:     return ($status,$data);
                   1417: }
                   1418: 
                   1419: ################################################
                   1420: ################################################
                   1421: 
                   1422: =pod
                   1423: 
1.89      matthew  1424: =item &ensure_current_full_data($sname,$sdom,$courseid)
                   1425: 
                   1426: Input: $sname, $sdom, $courseid
                   1427: 
                   1428: Output: $status
                   1429: 
                   1430: This routine ensures the fulldata (the data from a lonnet::dump, not a
                   1431: lonnet::currentdump) for a given student is up to date.
1.113     matthew  1432: The $student_table is queried to determine the time of the last update.  
1.89      matthew  1433: If the students fulldata is out of date, &update_full_student_data() is
                   1434: called.  
                   1435: 
                   1436: The return value from the call to &update_full_student_data() is returned.
                   1437: 
                   1438: =cut
                   1439: 
                   1440: ################################################
                   1441: ################################################
                   1442: sub ensure_current_full_data {
                   1443:     my ($sname,$sdom,$courseid) = @_;
                   1444:     my $status = 'okay';   # return value
                   1445:     #
1.146     albertel 1446:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.89      matthew  1447:     &ensure_tables_are_set_up($courseid);
                   1448:     #
                   1449:     # Get the update time for the user
                   1450:     my $modifiedtime = &Apache::lonnet::GetFileTimestamp
                   1451:         ($sdom,$sname,$courseid.'.db',
                   1452:          $Apache::lonnet::perlvar{'lonUsersDir'});
                   1453:     #
                   1454:     my $student_id = &get_student_id($sname,$sdom);
1.113     matthew  1455:     my @Result = &Apache::lonmysql::get_rows($student_table,
1.89      matthew  1456:                                              "student_id ='$student_id'");
                   1457:     my $updatetime;
                   1458:     if (@Result && ref($Result[0]) eq 'ARRAY') {
1.113     matthew  1459:         $updatetime = $Result[0]->[6];
1.89      matthew  1460:     }
                   1461:     if (! defined($updatetime) || $modifiedtime > $updatetime) {
                   1462:         $status = &update_full_student_data($sname,$sdom,$courseid);
                   1463:     }
                   1464:     return $status;
                   1465: }
                   1466: 
                   1467: ################################################
                   1468: ################################################
                   1469: 
                   1470: =pod
                   1471: 
1.57      matthew  1472: =item &get_student_data_from_performance_cache()
                   1473: 
                   1474: Input: $sname, $sdom, $symb, $courseid
                   1475: 
                   1476: Output: hash reference containing the data for the given student.
                   1477: If $symb is undef, all the students data is returned.
                   1478: 
                   1479: This routine is the heart of the local caching system.  See the description
                   1480: of $performance_table, $symb_table, $student_table, and $part_table.  The
                   1481: main task is building the MySQL request.  The tables appear in the request
                   1482: in the order in which they should be parsed by MySQL.  When searching
                   1483: on a student the $student_table is used to locate the 'student_id'.  All
                   1484: rows in $performance_table which have a matching 'student_id' are returned,
                   1485: with data from $part_table and $symb_table which match the entries in
                   1486: $performance_table, 'part_id' and 'symb_id'.  When searching on a symb,
                   1487: the $symb_table is processed first, with matching rows grabbed from 
                   1488: $performance_table and filled in from $part_table and $student_table in
                   1489: that order.  
                   1490: 
                   1491: Running 'EXPLAIN ' on the 'SELECT' statements generated can be quite 
                   1492: interesting, especially if you play with the order the tables are listed.  
                   1493: 
                   1494: =cut
                   1495: 
                   1496: ################################################
                   1497: ################################################
                   1498: sub get_student_data_from_performance_cache {
                   1499:     my ($sname,$sdom,$symb,$courseid)=@_;
                   1500:     my $student = $sname.':'.$sdom if (defined($sname) && defined($sdom));
1.61      matthew  1501:     &setup_table_names($courseid);
1.57      matthew  1502:     #
                   1503:     # Return hash
                   1504:     my $studentdata;
                   1505:     #
                   1506:     my $dbh = &Apache::lonmysql::get_dbh();
                   1507:     my $request = "SELECT ".
1.73      matthew  1508:         "d.symb,a.part,a.solved,a.tries,a.awarded,a.award,a.awarddetail,".
1.63      matthew  1509:             "a.timestamp ";
1.57      matthew  1510:     if (defined($student)) {
                   1511:         $request .= "FROM $student_table AS b ".
                   1512:             "LEFT JOIN $performance_table AS a ON b.student_id=a.student_id ".
1.73      matthew  1513: #            "LEFT JOIN $part_table AS c ON c.part_id = a.part_id ".
1.57      matthew  1514:             "LEFT JOIN $symb_table AS d ON d.symb_id = a.symb_id ".
                   1515:                 "WHERE student='$student'";
                   1516:         if (defined($symb) && $symb ne '') {
1.67      matthew  1517:             $request .= " AND d.symb=".$dbh->quote($symb);
1.57      matthew  1518:         }
                   1519:     } elsif (defined($symb) && $symb ne '') {
                   1520:         $request .= "FROM $symb_table as d ".
                   1521:             "LEFT JOIN $performance_table AS a ON d.symb_id=a.symb_id ".
1.73      matthew  1522: #            "LEFT JOIN $part_table    AS c ON c.part_id = a.part_id ".
1.57      matthew  1523:             "LEFT JOIN $student_table AS b ON b.student_id = a.student_id ".
                   1524:                 "WHERE symb='".$dbh->quote($symb)."'";
                   1525:     }
                   1526:     my $starttime = Time::HiRes::time;
                   1527:     my $rows_retrieved = 0;
                   1528:     my $sth = $dbh->prepare($request);
                   1529:     $sth->execute();
                   1530:     if ($sth->err()) {
                   1531:         &Apache::lonnet::logthis("Unable to execute MySQL request:");
                   1532:         &Apache::lonnet::logthis("\n".$request."\n");
                   1533:         &Apache::lonnet::logthis("error is:".$sth->errstr());
                   1534:         return undef;
                   1535:     }
                   1536:     foreach my $row (@{$sth->fetchall_arrayref}) {
                   1537:         $rows_retrieved++;
1.63      matthew  1538:         my ($symb,$part,$solved,$tries,$awarded,$award,$awarddetail,$time) = 
1.57      matthew  1539:             (@$row);
                   1540:         my $base = 'resource.'.$part;
                   1541:         $studentdata->{$symb}->{$base.'.solved'}  = $solved;
                   1542:         $studentdata->{$symb}->{$base.'.tries'}   = $tries;
                   1543:         $studentdata->{$symb}->{$base.'.awarded'} = $awarded;
                   1544:         $studentdata->{$symb}->{$base.'.award'}   = $award;
                   1545:         $studentdata->{$symb}->{$base.'.awarddetail'} = $awarddetail;
                   1546:         $studentdata->{$symb}->{'timestamp'} = $time if (defined($time) && $time ne '');
1.67      matthew  1547:     }
1.97      matthew  1548:     ## Get misc parameters
                   1549:     $request = 'SELECT c.symb,a.parameter,a.value '.
                   1550:         "FROM $student_table AS b ".
                   1551:         "LEFT JOIN $parameters_table AS a ON b.student_id=a.student_id ".
                   1552:         "LEFT JOIN $symb_table AS c ON c.symb_id = a.symb_id ".
                   1553:         "WHERE student='$student'";
                   1554:     if (defined($symb) && $symb ne '') {
                   1555:         $request .= " AND c.symb=".$dbh->quote($symb);
                   1556:     }
                   1557:     $sth = $dbh->prepare($request);
                   1558:     $sth->execute();
                   1559:     if ($sth->err()) {
                   1560:         &Apache::lonnet::logthis("Unable to execute MySQL request:");
                   1561:         &Apache::lonnet::logthis("\n".$request."\n");
                   1562:         &Apache::lonnet::logthis("error is:".$sth->errstr());
                   1563:         if (defined($symb) && $symb ne '') {
                   1564:             $studentdata = $studentdata->{$symb};
                   1565:         }
                   1566:         return $studentdata;
                   1567:     }
                   1568:     #
                   1569:     foreach my $row (@{$sth->fetchall_arrayref}) {
                   1570:         $rows_retrieved++;
                   1571:         my ($symb,$parameter,$value) = (@$row);
                   1572:         $studentdata->{$symb}->{$parameter}  = $value;
                   1573:     }
                   1574:     #
1.67      matthew  1575:     if (defined($symb) && $symb ne '') {
                   1576:         $studentdata = $studentdata->{$symb};
1.57      matthew  1577:     }
                   1578:     return $studentdata;
                   1579: }
                   1580: 
                   1581: ################################################
                   1582: ################################################
                   1583: 
                   1584: =pod
                   1585: 
                   1586: =item &get_current_state()
                   1587: 
                   1588: Input: $sname,$sdom,$symb,$courseid
                   1589: 
                   1590: Output: Described below
1.46      matthew  1591: 
1.47      matthew  1592: Retrieve the current status of a students performance.  $sname and
1.46      matthew  1593: $sdom are the only required parameters.  If $symb is undef the results
1.47      matthew  1594: of an &Apache::lonnet::currentdump() will be returned.  
1.46      matthew  1595: If $courseid is undef it will be retrieved from the environment.
                   1596: 
                   1597: The return structure is based on &Apache::lonnet::currentdump.  If
                   1598: $symb is unspecified, all the students data is returned in a hash of
                   1599: the form:
                   1600: ( 
                   1601:   symb1 => { param1 => value1, param2 => value2 ... },
                   1602:   symb2 => { param1 => value1, param2 => value2 ... },
                   1603: )
                   1604: 
                   1605: If $symb is specified, a hash of 
                   1606: (
                   1607:   param1 => value1, 
                   1608:   param2 => value2,
                   1609: )
                   1610: is returned.
                   1611: 
1.57      matthew  1612: If no data is found for $symb, or if the student has no performance data,
1.46      matthew  1613: an empty list is returned.
                   1614: 
                   1615: =cut
                   1616: 
                   1617: ################################################
                   1618: ################################################
                   1619: sub get_current_state {
1.47      matthew  1620:     my ($sname,$sdom,$symb,$courseid,$forcedownload)=@_;
                   1621:     #
1.146     albertel 1622:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.47      matthew  1623:     #
1.61      matthew  1624:     return () if (! defined($sname) || ! defined($sdom));
                   1625:     #
1.57      matthew  1626:     my ($status,$data) = &ensure_current_data($sname,$sdom,$courseid);
1.77      matthew  1627: #    &Apache::lonnet::logthis
                   1628: #        ('sname = '.$sname.
                   1629: #         ' domain = '.$sdom.
                   1630: #         ' status = '.$status.
                   1631: #         ' data is '.(defined($data)?'defined':'undefined'));
1.73      matthew  1632: #    while (my ($symb,$hash) = each(%$data)) {
                   1633: #        &Apache::lonnet::logthis($symb."\n----------------------------------");
                   1634: #        while (my ($key,$value) = each (%$hash)) {
                   1635: #            &Apache::lonnet::logthis("   ".$key." = ".$value);
                   1636: #        }
                   1637: #    }
1.47      matthew  1638:     #
1.79      matthew  1639:     if (defined($data) && defined($symb) && ref($data->{$symb})) {
                   1640:         return %{$data->{$symb}};
                   1641:     } elsif (defined($data) && ! defined($symb) && ref($data)) {
                   1642:         return %$data;
                   1643:     } 
                   1644:     if ($status eq 'no data') {
1.57      matthew  1645:         return ();
                   1646:     } else {
                   1647:         if ($status ne 'okay' && $status ne '') {
                   1648:             &Apache::lonnet::logthis('status = '.$status);
1.47      matthew  1649:             return ();
                   1650:         }
1.57      matthew  1651:         my $returnhash = &get_student_data_from_performance_cache($sname,$sdom,
                   1652:                                                       $symb,$courseid);
                   1653:         return %$returnhash if (defined($returnhash));
1.46      matthew  1654:     }
1.57      matthew  1655:     return ();
1.61      matthew  1656: }
                   1657: 
                   1658: ################################################
                   1659: ################################################
                   1660: 
                   1661: =pod
                   1662: 
                   1663: =item &get_problem_statistics()
                   1664: 
                   1665: Gather data on a given problem.  The database is assumed to be 
                   1666: populated and all local caching variables are assumed to be set
                   1667: properly.  This means you need to call &ensure_current_data for
                   1668: the students you are concerned with prior to calling this routine.
                   1669: 
1.124     matthew  1670: Inputs: $Sections, $status, $symb, $part, $courseid, $starttime, $endtime
1.61      matthew  1671: 
1.64      matthew  1672: =over 4
                   1673: 
1.124     matthew  1674: =item $Sections Array ref containing section names for students.  
                   1675: 'all' is allowed to be the first (and only) item in the array.
                   1676: 
                   1677: =item $status String describing the status of students
1.64      matthew  1678: 
                   1679: =item $symb is the symb for the problem.
                   1680: 
                   1681: =item $part is the part id you need statistics for
                   1682: 
                   1683: =item $courseid is the course id, of course!
                   1684: 
1.122     matthew  1685: =item $starttime and $endtime are unix times which to use to limit
                   1686: the statistical data.
                   1687: 
1.64      matthew  1688: =back
                   1689: 
1.66      matthew  1690: Outputs: See the code for up to date information.  A hash reference is
                   1691: returned.  The hash has the following keys defined:
1.64      matthew  1692: 
                   1693: =over 4
                   1694: 
1.66      matthew  1695: =item num_students The number of students attempting the problem
                   1696:       
                   1697: =item tries The total number of tries for the students
                   1698:       
                   1699: =item max_tries The maximum number of tries taken
                   1700:       
                   1701: =item mean_tries The average number of tries
                   1702:       
                   1703: =item num_solved The number of students able to solve the problem
                   1704:       
                   1705: =item num_override The number of students whose answer is 'correct_by_override'
                   1706:       
                   1707: =item deg_of_diff The degree of difficulty of the problem
                   1708:       
                   1709: =item std_tries The standard deviation of the number of tries
                   1710:       
                   1711: =item skew_tries The skew of the number of tries
1.64      matthew  1712: 
1.66      matthew  1713: =item per_wrong The number of students attempting the problem who were not
                   1714: able to answer it correctly.
1.64      matthew  1715: 
                   1716: =back
                   1717: 
1.61      matthew  1718: =cut
                   1719: 
                   1720: ################################################
                   1721: ################################################
                   1722: sub get_problem_statistics {
1.122     matthew  1723:     my ($Sections,$status,$symb,$part,$courseid,$starttime,$endtime) = @_;
1.61      matthew  1724:     return if (! defined($symb) || ! defined($part));
1.146     albertel 1725:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.61      matthew  1726:     #
1.100     matthew  1727:     &setup_table_names($courseid);
1.61      matthew  1728:     my $symb_id = &get_symb_id($symb);
                   1729:     my $part_id = &get_part_id($part);
                   1730:     my $stats_table = $courseid.'_problem_stats';
                   1731:     #
                   1732:     my $dbh = &Apache::lonmysql::get_dbh();
                   1733:     return undef if (! defined($dbh));
                   1734:     #
1.123     matthew  1735:     # Clean out the table
1.61      matthew  1736:     $dbh->do('DROP TABLE '.$stats_table);  # May return an error
                   1737:     my $request = 
1.115     matthew  1738:         'CREATE TEMPORARY TABLE '.$stats_table.' '.
                   1739:         'SELECT a.student_id,a.solved,a.award,a.awarded,a.tries '.
                   1740:         'FROM '.$performance_table.' AS a ';
1.123     matthew  1741:     #
                   1742:     # See if we need to include some requirements on the students
1.115     matthew  1743:     if ((defined($Sections) && lc($Sections->[0]) ne 'all') || 
                   1744:         (defined($status)   && lc($status)        ne 'any')) {
                   1745:         $request .= 'NATURAL LEFT JOIN '.$student_table.' AS b ';
                   1746:     }
                   1747:     $request .= ' WHERE a.symb_id='.$symb_id.' AND a.part_id='.$part_id;
1.123     matthew  1748:     #
                   1749:     # Limit the students included to those specified
1.115     matthew  1750:     if (defined($Sections) && lc($Sections->[0]) ne 'all') {
1.64      matthew  1751:         $request .= ' AND ('.
1.115     matthew  1752:             join(' OR ', map { "b.section='".$_."'" } @$Sections
1.64      matthew  1753:                  ).')';
                   1754:     }
1.115     matthew  1755:     if (defined($status) && lc($status) ne 'any') {
                   1756:         $request .= " AND b.status='".$status."'";
1.122     matthew  1757:     }
                   1758:     #
1.123     matthew  1759:     # Limit by starttime and endtime
1.122     matthew  1760:     my $time_requirements = undef;
                   1761:     if (defined($starttime)) {
                   1762:         $time_requirements .= 'a.timestamp>='.$starttime;
                   1763:         if (defined($endtime)) {
                   1764:             $time_requirements .= ' AND a.timestamp<='.$endtime;
                   1765:         }
                   1766:     } elsif (defined($endtime)) {
                   1767:         $time_requirements .= 'a.timestamp<='.$endtime;
                   1768:     }
                   1769:     if (defined($time_requirements)) {
                   1770:         $request .= ' AND '.$time_requirements;
1.115     matthew  1771:     }
1.123     matthew  1772:     #
                   1773:     # Finally, execute the request to create the temporary table
1.61      matthew  1774:     $dbh->do($request);
1.123     matthew  1775:     #
                   1776:     # Collect the first suite of statistics
1.128     matthew  1777:     $request = 'SELECT COUNT(*),SUM(tries),'.
                   1778:         'AVG(tries),STD(tries) '.
1.109     matthew  1779:         'FROM '.$stats_table;
1.128     matthew  1780:     my ($num,$tries,$mean,$STD) = &execute_SQL_request
1.109     matthew  1781:         ($dbh,$request);
1.128     matthew  1782:     #
                   1783:     $request = 'SELECT MAX(tries),MIN(tries) FROM '.$stats_table.
                   1784:         ' WHERE awarded>0';
                   1785:     if (defined($time_requirements)) {
                   1786:         $request .= ' AND '.$time_requirements;
                   1787:     }
                   1788:     my ($max,$min) = &execute_SQL_request($dbh,$request);
                   1789:     #
1.109     matthew  1790:     $request = 'SELECT SUM(awarded) FROM '.$stats_table;
1.128     matthew  1791:     if (defined($time_requirements)) {
                   1792:         $request .= ' AND '.$time_requirements;
                   1793:     }
1.109     matthew  1794:     my ($Solved) = &execute_SQL_request($dbh,$request);
1.128     matthew  1795:     #
1.109     matthew  1796:     $request = 'SELECT SUM(awarded) FROM '.$stats_table.
                   1797:         " WHERE solved='correct_by_override'";
1.128     matthew  1798:     if (defined($time_requirements)) {
                   1799:         $request .= ' AND '.$time_requirements;
                   1800:     }
1.109     matthew  1801:     my ($solved) = &execute_SQL_request($dbh,$request);
                   1802:     #
1.133     matthew  1803:     $Solved -= $solved;
                   1804:     #
1.61      matthew  1805:     $num    = 0 if (! defined($num));
                   1806:     $tries  = 0 if (! defined($tries));
1.128     matthew  1807:     $max    = 0 if (! defined($max));
                   1808:     $min    = 0 if (! defined($min));
1.61      matthew  1809:     $STD    = 0 if (! defined($STD));
1.133     matthew  1810:     $Solved = 0 if (! defined($Solved) || $Solved < 0);
1.61      matthew  1811:     $solved = 0 if (! defined($solved));
                   1812:     #
1.123     matthew  1813:     # Compute the more complicated statistics
1.61      matthew  1814:     my $DegOfDiff = 'nan';
1.66      matthew  1815:     $DegOfDiff = 1-($Solved)/$tries if ($tries>0);
1.123     matthew  1816:     #
1.61      matthew  1817:     my $SKEW = 'nan';
1.66      matthew  1818:     my $wrongpercent = 0;
1.128     matthew  1819:     my $numwrong = 'nan';
1.61      matthew  1820:     if ($num > 0) {
                   1821:         ($SKEW) = &execute_SQL_request($dbh,'SELECT SQRT(SUM('.
                   1822:                                      'POWER(tries - '.$STD.',3)'.
                   1823:                                      '))/'.$num.' FROM '.$stats_table);
1.128     matthew  1824:         $numwrong = $num-$Solved;
                   1825:         $wrongpercent=int(10*100*$numwrong/$num)/10;
1.61      matthew  1826:     }
                   1827:     #
1.123     matthew  1828:     # Drop the temporary table
                   1829:     $dbh->do('DROP TABLE '.$stats_table);  # May return an error
1.81      matthew  1830:     #
                   1831:     # Return result
1.66      matthew  1832:     return { num_students => $num,
                   1833:              tries        => $tries,
1.128     matthew  1834:              max_tries    => $max,
                   1835:              min_tries    => $min,
1.66      matthew  1836:              mean_tries   => $mean,
                   1837:              std_tries    => $STD,
                   1838:              skew_tries   => $SKEW,
                   1839:              num_solved   => $Solved,
                   1840:              num_override => $solved,
1.128     matthew  1841:              num_wrong    => $numwrong,
1.66      matthew  1842:              per_wrong    => $wrongpercent,
1.81      matthew  1843:              deg_of_diff  => $DegOfDiff };
1.61      matthew  1844: }
                   1845: 
1.127     matthew  1846: ##
                   1847: ## This is a helper for get_statistics
1.61      matthew  1848: sub execute_SQL_request {
                   1849:     my ($dbh,$request)=@_;
                   1850: #    &Apache::lonnet::logthis($request);
                   1851:     my $sth = $dbh->prepare($request);
1.153     albertel 1852:     if (!$sth) {
                   1853: 	die($dbh->errstr . " SQL: $request");
                   1854:     }
1.61      matthew  1855:     $sth->execute();
                   1856:     my $row = $sth->fetchrow_arrayref();
                   1857:     if (ref($row) eq 'ARRAY' && scalar(@$row)>0) {
                   1858:         return @$row;
                   1859:     }
                   1860:     return ();
                   1861: }
1.123     matthew  1862: 
1.127     matthew  1863: ######################################################
                   1864: ######################################################
                   1865: 
                   1866: =pod
                   1867: 
                   1868: =item &populate_weight_table
                   1869: 
                   1870: =cut
                   1871: 
                   1872: ######################################################
                   1873: ######################################################
                   1874: sub populate_weight_table {
                   1875:     my ($courseid) = @_;
                   1876:     if (! defined($courseid)) {
1.146     albertel 1877:         $courseid = $env{'request.course.id'};
1.127     matthew  1878:     }
                   1879:     #
                   1880:     &setup_table_names($courseid);
1.144     matthew  1881:     my $navmap = Apache::lonnavmaps::navmap->new();
                   1882:     if (!defined($navmap)) {
                   1883:         &Apache::lonnet::logthis('loncoursedata::populate_weight_table:'.$/.
                   1884:                                  '  unable to get navmaps resource'.$/.
                   1885:                                  '  '.join(' ',(caller)));
                   1886:         return;
                   1887:     }
                   1888:     my @sequences = $navmap->retrieveResources(undef,
                   1889:                                                sub { shift->is_map(); },1,0,1);
                   1890:     my @resources;
                   1891:     foreach my $seq (@sequences) {
                   1892:         push(@resources,$navmap->retrieveResources($seq,
                   1893:                                                    sub {shift->is_problem();},
                   1894:                                                    0,0,0));
                   1895:     }
                   1896:     if (! scalar(@resources)) {
                   1897:         &Apache::lonnet::logthis('loncoursedata::populate_weight_table:'.$/.
                   1898:                                  ' no resources returned for '.$courseid);
1.127     matthew  1899:         return;
                   1900:     }
                   1901:     #       Since we use lonnet::EXT to retrieve problem weights,
                   1902:     #       to ensure current data we must clear the caches out.
                   1903:     &Apache::lonnet::clear_EXT_cache_status();
                   1904:     my $dbh = &Apache::lonmysql::get_dbh();
                   1905:     my $request = 'INSERT IGNORE INTO '.$weight_table.
                   1906:         "(symb_id,part_id,weight) VALUES ";
                   1907:     my $weight;
1.144     matthew  1908:     foreach my $res (@resources) {
                   1909:         my $symb_id = &get_symb_id($res->symb);
                   1910:         foreach my $part (@{$res->parts}) {
1.127     matthew  1911:             my $part_id = &get_part_id($part);
                   1912:             $weight = &Apache::lonnet::EXT('resource.'.$part.'.weight',
1.144     matthew  1913:                                            $res->symb,
1.127     matthew  1914:                                            undef,undef,undef);
                   1915:             if (!defined($weight) || ($weight eq '')) { 
                   1916:                 $weight=1;
                   1917:             }
                   1918:             $request .= "('".$symb_id."','".$part_id."','".$weight."'),";
                   1919:         }
                   1920:     }
                   1921:     $request =~ s/(,)$//;
                   1922: #    &Apache::lonnet::logthis('request = '.$/.$request);
                   1923:     $dbh->do($request);
                   1924:     if ($dbh->err()) {
                   1925:         &Apache::lonnet::logthis("error ".$dbh->errstr().
                   1926:                                  " occured executing \n".
                   1927:                                  $request);
                   1928:     }
                   1929:     return;
                   1930: }
                   1931: 
                   1932: ##########################################################
                   1933: ##########################################################
1.61      matthew  1934: 
1.127     matthew  1935: =pod
                   1936: 
1.129     matthew  1937: =item &limit_by_start_end_times
                   1938: 
                   1939: Build SQL WHERE condition which limits the data collected by the start
                   1940: and end times provided
                   1941: 
                   1942: Inputs: $starttime, $endtime, $table
                   1943: 
                   1944: Returns: $time_limits
                   1945: 
                   1946: =cut
                   1947: 
                   1948: ##########################################################
                   1949: ##########################################################
                   1950: sub limit_by_start_end_time {
                   1951:     my ($starttime,$endtime,$table) = @_;
                   1952:     my $time_requirements = undef;
                   1953:     if (defined($starttime)) {
                   1954:         $time_requirements .= $table.".timestamp>='".$starttime."'";
                   1955:         if (defined($endtime)) {
                   1956:             $time_requirements .= " AND ".$table.".timestamp<='".$endtime."'";
                   1957:         }
                   1958:     } elsif (defined($endtime)) {
                   1959:         $time_requirements .= $table.".timestamp<='".$endtime."'";
                   1960:     }
                   1961:     return $time_requirements;
                   1962: }
                   1963: 
                   1964: ##########################################################
                   1965: ##########################################################
                   1966: 
                   1967: =pod
                   1968: 
1.127     matthew  1969: =item &limit_by_section_and_status
                   1970: 
                   1971: Build SQL WHERE condition which limits the data collected by section and
                   1972: student status.
                   1973: 
                   1974: Inputs: $Sections (array ref)
                   1975:     $enrollment (string: 'any', 'expired', 'active')
                   1976:     $tablename The name of the table that holds the student data
                   1977: 
                   1978: Returns: $student_requirements,$enrollment_requirements
                   1979: 
                   1980: =cut
                   1981: 
                   1982: ##########################################################
                   1983: ##########################################################
                   1984: sub limit_by_section_and_status {
                   1985:     my ($Sections,$enrollment,$tablename) = @_;
                   1986:     my $student_requirements = undef;
                   1987:     if ( (defined($Sections) && $Sections->[0] ne 'all')) {
                   1988:         $student_requirements = '('.
                   1989:             join(' OR ', map { $tablename.".section='".$_."'" } @$Sections
                   1990:                  ).')';
                   1991:     }
                   1992:     #
                   1993:     my $enrollment_requirements=undef;
                   1994:     if (defined($enrollment) && $enrollment ne 'Any') {
                   1995:         $enrollment_requirements = $tablename.".status='".$enrollment."'";
                   1996:     }
                   1997:     return ($student_requirements,$enrollment_requirements);
                   1998: }
                   1999: 
                   2000: ######################################################
                   2001: ######################################################
                   2002: 
                   2003: =pod
                   2004: 
                   2005: =item rank_students_by_scores_on_resources
                   2006: 
                   2007: Inputs: 
                   2008:     $resources: array ref of hash ref.  Each hash ref needs key 'symb'.
                   2009:     $Sections: array ref of sections to include,
                   2010:     $enrollment: string,
                   2011:     $courseid (may be omitted)
1.154     bowersj2 2012:     $starttime (may be omitted)
                   2013:     $endtime (may be omitted)
                   2014:     $has_award_for (may be omitted)
1.127     matthew  2015: 
                   2016: Returns; An array of arrays.  The sub arrays contain a student name and
1.154     bowersj2 2017: their score on the resources. $starttime and $endtime constrain the
                   2018: list to awards obtained during the given time limits. $has_score_on
                   2019: constrains the list to those students who at least attempted the
                   2020: resource identified by the given symb, which is used to filter out
                   2021: such students for statistics that would be adversely affected by such
                   2022: students. 
1.127     matthew  2023: 
                   2024: =cut
                   2025: 
                   2026: ######################################################
                   2027: ######################################################
                   2028: sub RNK_student { return 0; };
                   2029: sub RNK_score   { return 1; };
                   2030: 
                   2031: sub rank_students_by_scores_on_resources {
1.154     bowersj2 2032:     my ($resources,$Sections,$enrollment,$courseid,$starttime,$endtime,$has_award_for) = @_;
1.127     matthew  2033:     return if (! defined($resources) || ! ref($resources) eq 'ARRAY');
                   2034:     if (! defined($courseid)) {
1.146     albertel 2035:         $courseid = $env{'request.course.id'};
1.127     matthew  2036:     }
                   2037:     #
                   2038:     &setup_table_names($courseid);
                   2039:     my $dbh = &Apache::lonmysql::get_dbh();
                   2040:     my ($section_limits,$enrollment_limits)=
                   2041:         &limit_by_section_and_status($Sections,$enrollment,'b');
                   2042:     my $symb_limits = '('.join(' OR ',map {'a.symb_id='.&get_symb_id($_);
                   2043:                                        } @$resources
                   2044:                                ).')';
1.154     bowersj2 2045:     my ($award_col, $award_join, $award_clause) = ('', '', '');
1.155     albertel 2046:     if ($has_award_for) {
1.154     bowersj2 2047:         my $resource_id = &get_symb_id($has_award_for);
                   2048:         $award_col = ", perf.awarded";
                   2049:         $award_join = "LEFT JOIN $performance_table AS perf ON perf.symb_id"
                   2050:             ." = $resource_id AND perf.student_id = b.student_id ";
                   2051:         $award_clause = "AND perf.awarded IS NOT NULL";
                   2052:     }
1.130     matthew  2053:     my $time_limits = &limit_by_start_end_time($starttime,$endtime,'a');
1.154     bowersj2 2054:     my $request = "SELECT b.student,SUM(a.awarded*w.weight) AS score "
                   2055:         ."$award_col FROM $performance_table AS a ".
                   2056:         "NATURAL LEFT JOIN $weight_table AS w ".
                   2057:         "LEFT JOIN $student_table AS b ON a.student_id=b.student_id ".
                   2058:         "$award_join WHERE ";
1.127     matthew  2059:     if (defined($section_limits)) {
                   2060:         $request .= $section_limits.' AND ';
                   2061:     }
                   2062:     if (defined($enrollment_limits)) {
                   2063:         $request .= $enrollment_limits.' AND ';
                   2064:     }
1.130     matthew  2065:     if (defined($time_limits)) {
                   2066:         $request .= $time_limits.' AND ';
                   2067:     }
1.127     matthew  2068:     if ($symb_limits ne '()') {
                   2069:         $request .= $symb_limits.' AND ';
                   2070:     }
                   2071:     $request =~ s/( AND )$//;   # Remove extra conjunction
                   2072:     $request =~ s/( WHERE )$//; # In case there were no limits placed on it
1.154     bowersj2 2073:     $request .= " $award_clause GROUP BY a.student_id ORDER BY score";
1.127     matthew  2074:     #&Apache::lonnet::logthis('request = '.$/.$request);
1.154     bowersj2 2075:     my $sth = $dbh->prepare($request) or die "Can't prepare $request";
1.127     matthew  2076:     $sth->execute();
                   2077:     my $rows = $sth->fetchall_arrayref();
                   2078:     return ($rows);
                   2079: }
                   2080: 
                   2081: ########################################################
                   2082: ########################################################
                   2083: 
                   2084: =pod
                   2085: 
                   2086: =item &get_sum_of_scores
                   2087: 
                   2088: Inputs: $resource (hash ref, needs {'symb'} key),
                   2089: $part, (the part id),
                   2090: $students (array ref, contents of array are scalars holding 'sname:sdom'),
                   2091: $courseid
                   2092: 
                   2093: Returns: the sum of the score on the problem part over the students and the
                   2094:    maximum possible value for the sum (taken from the weight table).
                   2095: 
                   2096: =cut
                   2097: 
                   2098: ########################################################
                   2099: ########################################################
                   2100: sub get_sum_of_scores {
1.143     matthew  2101:     my ($symb,$part,$students,$courseid,$starttime,$endtime) = @_;
1.127     matthew  2102:     if (! defined($courseid)) {
1.146     albertel 2103:         $courseid = $env{'request.course.id'};
1.127     matthew  2104:     }
1.138     matthew  2105:     if (defined($students) && 
                   2106:         ((@$students == 0) ||
                   2107:          (@$students == 1 && (! defined($students->[0]) || 
                   2108:                               $students->[0] eq ''))
                   2109:          )
                   2110:         ){
                   2111:         undef($students);
                   2112:     }
1.127     matthew  2113:     #
                   2114:     &setup_table_names($courseid);
                   2115:     my $dbh = &Apache::lonmysql::get_dbh();
1.130     matthew  2116:     my $time_limits = &limit_by_start_end_time($starttime,$endtime,'a');
1.127     matthew  2117:     my $request = 'SELECT SUM(a.awarded*w.weight),SUM(w.weight) FROM '.
                   2118:         $performance_table.' AS a '.
                   2119:         'NATURAL LEFT JOIN '.$weight_table.' AS w ';
1.143     matthew  2120:     $request .= 'WHERE a.symb_id='.&get_symb_id($symb).
1.127     matthew  2121:         ' AND a.part_id='.&get_part_id($part);
1.130     matthew  2122:     if (defined($time_limits)) {
                   2123:         $request .= ' AND '.$time_limits;
                   2124:     }
1.127     matthew  2125:     if (defined($students)) {
                   2126:         $request .= ' AND ('.
                   2127:             join(' OR ',map {'a.student_id='.&get_student_id(split(':',$_));
                   2128:                          } @$students).
                   2129:                              ')';
                   2130:     }
                   2131:     my $sth = $dbh->prepare($request);
                   2132:     $sth->execute();
                   2133:     my $rows = $sth->fetchrow_arrayref();
                   2134:     if ($dbh->err) {
1.138     matthew  2135:         &Apache::lonnet::logthis('error 1 = '.$dbh->errstr());
                   2136:         &Apache::lonnet::logthis('prepared then executed, fetchrow_arrayrefed'.
                   2137:                                  $/.$request);
1.127     matthew  2138:         return (undef,undef);
                   2139:     }
                   2140:     return ($rows->[0],$rows->[1]);
                   2141: }
                   2142: 
1.129     matthew  2143: ########################################################
                   2144: ########################################################
                   2145: 
                   2146: =pod
                   2147: 
                   2148: =item &score_stats
                   2149: 
                   2150: Inputs: $Sections, $enrollment, $symbs, $starttime,
                   2151:         $endtime, $courseid
                   2152: 
                   2153: $Sections, $enrollment, $starttime, $endtime, and $courseid are the same as 
                   2154: elsewhere in this module.  
                   2155: $symbs is an array ref of symbs
                   2156: 
                   2157: Returns: minimum, maximum, mean, s.d., number of students, and maximum
                   2158:   possible of student scores on the given resources
                   2159: 
                   2160: =cut
                   2161: 
                   2162: ########################################################
                   2163: ########################################################
                   2164: sub score_stats {
                   2165:     my ($Sections,$enrollment,$symbs,$starttime,$endtime,$courseid)=@_;
                   2166:     if (! defined($courseid)) {
1.146     albertel 2167:         $courseid = $env{'request.course.id'};
1.129     matthew  2168:     }
                   2169:     #
                   2170:     &setup_table_names($courseid);
                   2171:     my $dbh = &Apache::lonmysql::get_dbh();
                   2172:     #
                   2173:     my ($section_limits,$enrollment_limits)=
                   2174:         &limit_by_section_and_status($Sections,$enrollment,'b');
                   2175:     my $time_limits = &limit_by_start_end_time($starttime,$endtime,'a');
                   2176:     my @Symbids = map { &get_symb_id($_); } @{$symbs};
                   2177:     #
                   2178:     my $stats_table = $courseid.'_problem_stats';
                   2179:     my $symb_restriction = join(' OR ',map {'a.symb_id='.$_;} @Symbids);
                   2180:     my $request = 'DROP TABLE '.$stats_table;
                   2181:     $dbh->do($request);
                   2182:     $request = 
                   2183:         'CREATE TEMPORARY TABLE '.$stats_table.' '.
                   2184:         'SELECT a.student_id,'.
                   2185:         'SUM(a.awarded*w.weight) AS score FROM '.
                   2186:         $performance_table.' AS a '.
                   2187:         'NATURAL LEFT JOIN '.$weight_table.' AS w '.
                   2188:         'LEFT JOIN '.$student_table.' AS b ON a.student_id=b.student_id '.
                   2189:         'WHERE ('.$symb_restriction.')';
                   2190:     if ($time_limits) {
                   2191:         $request .= ' AND '.$time_limits;
                   2192:     }
                   2193:     if ($section_limits) {
                   2194:         $request .= ' AND '.$section_limits;
                   2195:     }
                   2196:     if ($enrollment_limits) {
                   2197:         $request .= ' AND '.$enrollment_limits;
                   2198:     }
                   2199:     $request .= ' GROUP BY a.student_id';
                   2200: #    &Apache::lonnet::logthis('request = '.$/.$request);
                   2201:     my $sth = $dbh->prepare($request);
                   2202:     $sth->execute();
                   2203:     $request = 
                   2204:         'SELECT AVG(score),STD(score),MAX(score),MIN(score),COUNT(score) '.
                   2205:         'FROM '.$stats_table;
                   2206:     my ($ave,$std,$max,$min,$count) = &execute_SQL_request($dbh,$request);
                   2207: #    &Apache::lonnet::logthis('request = '.$/.$request);
                   2208:     
                   2209:     $request = 'SELECT SUM(weight) FROM '.$weight_table.
1.152     bowersj2 2210:         ' AS a WHERE ('.$symb_restriction.')';
1.129     matthew  2211:     my ($max_possible) = &execute_SQL_request($dbh,$request);
                   2212:     # &Apache::lonnet::logthis('request = '.$/.$request);
                   2213:     return($min,$max,$ave,$std,$count,$max_possible);
                   2214: }
                   2215: 
                   2216: 
                   2217: ########################################################
                   2218: ########################################################
                   2219: 
                   2220: =pod
                   2221: 
                   2222: =item &count_stats
                   2223: 
                   2224: Inputs: $Sections, $enrollment, $symbs, $starttime,
                   2225:         $endtime, $courseid
                   2226: 
                   2227: $Sections, $enrollment, $starttime, $endtime, and $courseid are the same as 
                   2228: elsewhere in this module.  
                   2229: $symbs is an array ref of symbs
                   2230: 
                   2231: Returns: minimum, maximum, mean, s.d., and number of students
                   2232:   of the number of items correct on the given resources
                   2233: 
                   2234: =cut
                   2235: 
                   2236: ########################################################
                   2237: ########################################################
                   2238: sub count_stats {
                   2239:     my ($Sections,$enrollment,$symbs,$starttime,$endtime,$courseid)=@_;
                   2240:     if (! defined($courseid)) {
1.146     albertel 2241:         $courseid = $env{'request.course.id'};
1.129     matthew  2242:     }
                   2243:     #
                   2244:     &setup_table_names($courseid);
                   2245:     my $dbh = &Apache::lonmysql::get_dbh();
                   2246:     #
                   2247:     my ($section_limits,$enrollment_limits)=
                   2248:         &limit_by_section_and_status($Sections,$enrollment,'b');
                   2249:     my $time_limits = &limit_by_start_end_time($starttime,$endtime,'a');
                   2250:     my @Symbids = map { &get_symb_id($_); } @{$symbs};
                   2251:     #
                   2252:     my $stats_table = $courseid.'_problem_stats';
                   2253:     my $symb_restriction = join(' OR ',map {'a.symb_id='.$_;} @Symbids);
                   2254:     my $request = 'DROP TABLE '.$stats_table;
                   2255:     $dbh->do($request);
                   2256:     $request = 
                   2257:         'CREATE TEMPORARY TABLE '.$stats_table.' '.
                   2258:         'SELECT a.student_id,'.
1.151     albertel 2259:         'SUM(a.awarded) AS count FROM '.
1.129     matthew  2260:         $performance_table.' AS a '.
                   2261:         'LEFT JOIN '.$student_table.' AS b ON a.student_id=b.student_id '.
1.151     albertel 2262:         'WHERE ('.$symb_restriction.')';
1.129     matthew  2263:     if ($time_limits) {
                   2264:         $request .= ' AND '.$time_limits;
                   2265:     }
                   2266:     if ($section_limits) {
                   2267:         $request .= ' AND '.$section_limits;
                   2268:     }
                   2269:     if ($enrollment_limits) {
                   2270:         $request .= ' AND '.$enrollment_limits;
                   2271:     }
                   2272:     $request .= ' GROUP BY a.student_id';
1.131     matthew  2273: #    &Apache::lonnet::logthis('request = '.$/.$request);
1.129     matthew  2274:     my $sth = $dbh->prepare($request);
                   2275:     $sth->execute();
                   2276:     $request = 
                   2277:         'SELECT AVG(count),STD(count),MAX(count),MIN(count),COUNT(count) '.
                   2278:         'FROM '.$stats_table;
                   2279:     my ($ave,$std,$max,$min,$count) = &execute_SQL_request($dbh,$request);
1.131     matthew  2280: #    &Apache::lonnet::logthis('request = '.$/.$request);
1.129     matthew  2281:     return($min,$max,$ave,$std,$count);
                   2282: }
1.127     matthew  2283: 
                   2284: ######################################################
                   2285: ######################################################
                   2286: 
                   2287: =pod
                   2288: 
                   2289: =item get_student_data
                   2290: 
                   2291: =cut
                   2292: 
                   2293: ######################################################
                   2294: ######################################################
1.105     matthew  2295: sub get_student_data {
                   2296:     my ($students,$courseid) = @_;
1.146     albertel 2297:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.105     matthew  2298:     &setup_table_names($courseid);
                   2299:     my $dbh = &Apache::lonmysql::get_dbh();
                   2300:     return undef if (! defined($dbh));
                   2301:     my $request = 'SELECT '.
                   2302:         'student_id, student '.
                   2303:         'FROM '.$student_table;
                   2304:     if (defined($students)) {
                   2305:         $request .= ' WHERE ('.
                   2306:             join(' OR ', map {'student_id='.
                   2307:                                   &get_student_id($_->{'username'},
                   2308:                                                   $_->{'domain'})
                   2309:                               } @$students
                   2310:                  ).')';
                   2311:     }
                   2312:     $request.= ' ORDER BY student_id';
                   2313:     my $sth = $dbh->prepare($request);
                   2314:     $sth->execute();
                   2315:     if ($dbh->err) {
1.138     matthew  2316:         &Apache::lonnet::logthis('error 2 = '.$dbh->errstr());
                   2317:         &Apache::lonnet::logthis('prepared then executed '.$/.$request);
1.105     matthew  2318:         return undef;
                   2319:     }
                   2320:     my $dataset = $sth->fetchall_arrayref();
                   2321:     if (ref($dataset) eq 'ARRAY' && scalar(@$dataset)>0) {
                   2322:         return $dataset;
                   2323:     }
                   2324: }
                   2325: 
1.108     matthew  2326: sub RD_student_id    { return 0; }
                   2327: sub RD_awarddetail   { return 1; }
                   2328: sub RD_response_eval { return 2; }
                   2329: sub RD_submission    { return 3; }
                   2330: sub RD_timestamp     { return 4; }
                   2331: sub RD_tries         { return 5; }
                   2332: sub RD_sname         { return 6; }
                   2333: 
                   2334: sub get_response_data {
1.126     matthew  2335:     my ($Sections,$enrollment,$symb,$response,$courseid) = @_;
1.103     matthew  2336:     return undef if (! defined($symb) || 
1.100     matthew  2337:                ! defined($response));
1.146     albertel 2338:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.100     matthew  2339:     #
                   2340:     &setup_table_names($courseid);
                   2341:     my $symb_id = &get_symb_id($symb);
1.137     matthew  2342:     if (! defined($symb_id)) {
                   2343:         &Apache::lonnet::logthis('Unable to find symb for '.$symb.' in '.$courseid);
                   2344:         return undef;
                   2345:     }
1.100     matthew  2346:     my $response_id = &get_part_id($response);
1.137     matthew  2347:     if (! defined($response_id)) {
                   2348:         &Apache::lonnet::logthis('Unable to find id for '.$response.' in '.$courseid);
                   2349:         return undef;
                   2350:     }
1.100     matthew  2351:     #
                   2352:     my $dbh = &Apache::lonmysql::get_dbh();
                   2353:     return undef if (! defined($dbh));
1.126     matthew  2354:     #
1.127     matthew  2355:     my ($student_requirements,$enrollment_requirements) = 
                   2356:         &limit_by_section_and_status($Sections,$enrollment,'d');
1.100     matthew  2357:     my $request = 'SELECT '.
1.105     matthew  2358:         'a.student_id, a.awarddetail, a.response_specific_value, '.
1.108     matthew  2359:         'a.submission, b.timestamp, c.tries, d.student '.
1.100     matthew  2360:         'FROM '.$fulldump_response_table.' AS a '.
                   2361:         'LEFT JOIN '.$fulldump_timestamp_table.' AS b '.
                   2362:         'ON a.symb_id=b.symb_id AND a.student_id=b.student_id AND '.
                   2363:         'a.transaction = b.transaction '.
                   2364:         'LEFT JOIN '.$fulldump_part_table.' AS c '.
                   2365:         'ON a.symb_id=c.symb_id AND a.student_id=c.student_id AND '.        
                   2366:         'a.part_id=c.part_id AND a.transaction = c.transaction '.
1.108     matthew  2367:         'LEFT JOIN '.$student_table.' AS d '.
                   2368:         'ON a.student_id=d.student_id '.
1.100     matthew  2369:         'WHERE '.
                   2370:         'a.symb_id='.$symb_id.' AND a.response_id='.$response_id;
1.126     matthew  2371:     if (defined($student_requirements) || defined($enrollment_requirements)) {
                   2372:         $request .= ' AND ';
                   2373:         if (defined($student_requirements)) {
                   2374:             $request .= $student_requirements.' AND ';
                   2375:         }
                   2376:         if (defined($enrollment_requirements)) {
                   2377:             $request .= $enrollment_requirements.' AND ';
                   2378:         }
                   2379:         $request =~ s/( AND )$//;
1.100     matthew  2380:     }
                   2381:     $request .= ' ORDER BY b.timestamp';
1.103     matthew  2382: #    &Apache::lonnet::logthis("request =\n".$request);
1.100     matthew  2383:     my $sth = $dbh->prepare($request);
                   2384:     $sth->execute();
1.105     matthew  2385:     if ($dbh->err) {
1.138     matthew  2386:         &Apache::lonnet::logthis('error 3 = '.$dbh->errstr());
                   2387:         &Apache::lonnet::logthis('prepared then executed '.$/.$request);
1.105     matthew  2388:         return undef;
                   2389:     }
1.100     matthew  2390:     my $dataset = $sth->fetchall_arrayref();
                   2391:     if (ref($dataset) eq 'ARRAY' && scalar(@$dataset)>0) {
1.117     matthew  2392:         # Clear the \'s from around the submission
                   2393:         for (my $i =0;$i<scalar(@$dataset);$i++) {
                   2394:             $dataset->[$i]->[3] =~ s/(\'$|^\')//g;
                   2395:         }
1.103     matthew  2396:         return $dataset;
1.100     matthew  2397:     }
1.118     matthew  2398: }
                   2399: 
                   2400: 
                   2401: sub RDs_awarddetail   { return 3; }
                   2402: sub RDs_submission    { return 2; }
                   2403: sub RDs_timestamp     { return 1; }
                   2404: sub RDs_tries         { return 0; }
1.119     matthew  2405: sub RDs_awarded       { return 4; }
1.118     matthew  2406: 
                   2407: sub get_response_data_by_student {
                   2408:     my ($student,$symb,$response,$courseid) = @_;
                   2409:     return undef if (! defined($symb) || 
                   2410:                      ! defined($response));
1.146     albertel 2411:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.118     matthew  2412:     #
                   2413:     &setup_table_names($courseid);
                   2414:     my $symb_id = &get_symb_id($symb);
                   2415:     my $response_id = &get_part_id($response);
                   2416:     #
                   2417:     my $student_id = &get_student_id($student->{'username'},
                   2418:                                      $student->{'domain'});
                   2419:     #
                   2420:     my $dbh = &Apache::lonmysql::get_dbh();
                   2421:     return undef if (! defined($dbh));
                   2422:     my $request = 'SELECT '.
1.119     matthew  2423:         'c.tries, b.timestamp, a.submission, a.awarddetail, e.awarded '.
1.118     matthew  2424:         'FROM '.$fulldump_response_table.' AS a '.
                   2425:         'LEFT JOIN '.$fulldump_timestamp_table.' AS b '.
                   2426:         'ON a.symb_id=b.symb_id AND a.student_id=b.student_id AND '.
                   2427:         'a.transaction = b.transaction '.
                   2428:         'LEFT JOIN '.$fulldump_part_table.' AS c '.
                   2429:         'ON a.symb_id=c.symb_id AND a.student_id=c.student_id AND '.        
                   2430:         'a.part_id=c.part_id AND a.transaction = c.transaction '.
                   2431:         'LEFT JOIN '.$student_table.' AS d '.
                   2432:         'ON a.student_id=d.student_id '.
1.119     matthew  2433:         'LEFT JOIN '.$performance_table.' AS e '.
                   2434:         'ON a.symb_id=e.symb_id AND a.part_id=e.part_id AND '.
                   2435:         'a.student_id=e.student_id AND c.tries=e.tries '.
1.118     matthew  2436:         'WHERE '.
                   2437:         'a.symb_id='.$symb_id.' AND a.response_id='.$response_id.
                   2438:         ' AND a.student_id='.$student_id.' ORDER BY b.timestamp';
1.125     matthew  2439: #    &Apache::lonnet::logthis("request =\n".$request);
1.118     matthew  2440:     my $sth = $dbh->prepare($request);
                   2441:     $sth->execute();
                   2442:     if ($dbh->err) {
1.138     matthew  2443:         &Apache::lonnet::logthis('error 4 = '.$dbh->errstr());
                   2444:         &Apache::lonnet::logthis('prepared then executed '.$/.$request);
1.118     matthew  2445:         return undef;
                   2446:     }
                   2447:     my $dataset = $sth->fetchall_arrayref();
                   2448:     if (ref($dataset) eq 'ARRAY' && scalar(@$dataset)>0) {
                   2449:         # Clear the \'s from around the submission
                   2450:         for (my $i =0;$i<scalar(@$dataset);$i++) {
                   2451:             $dataset->[$i]->[2] =~ s/(\'$|^\')//g;
                   2452:         }
                   2453:         return $dataset;
                   2454:     }
                   2455:     return undef; # error occurred
1.106     matthew  2456: }
1.108     matthew  2457: 
                   2458: sub RT_student_id { return 0; }
                   2459: sub RT_awarded    { return 1; }
                   2460: sub RT_tries      { return 2; }
                   2461: sub RT_timestamp  { return 3; }
1.106     matthew  2462: 
                   2463: sub get_response_time_data {
1.142     matthew  2464:     my ($sections,$enrollment,$symb,$part,$courseid) = @_;
1.106     matthew  2465:     return undef if (! defined($symb) || 
1.107     matthew  2466:                      ! defined($part));
1.146     albertel 2467:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.106     matthew  2468:     #
                   2469:     &setup_table_names($courseid);
                   2470:     my $symb_id = &get_symb_id($symb);
1.142     matthew  2471:     if (! defined($symb_id)) {
                   2472:         &Apache::lonnet::logthis('Unable to find symb for '.$symb.' in '.$courseid);
                   2473:         return undef;
                   2474:     }
1.107     matthew  2475:     my $part_id = &get_part_id($part);
1.142     matthew  2476:     if (! defined($part_id)) {
                   2477:         &Apache::lonnet::logthis('Unable to find id for '.$part.' in '.$courseid);
                   2478:         return undef;
                   2479:     }
1.106     matthew  2480:     #
                   2481:     my $dbh = &Apache::lonmysql::get_dbh();
                   2482:     return undef if (! defined($dbh));
1.142     matthew  2483:     my ($student_requirements,$enrollment_requirements) = 
                   2484:         &limit_by_section_and_status($sections,$enrollment,'d');
1.106     matthew  2485:     my $request = 'SELECT '.
1.107     matthew  2486:         'a.student_id, a.awarded, a.tries, b.timestamp '.
                   2487:         'FROM '.$fulldump_part_table.' AS a '.
1.142     matthew  2488:         'LEFT JOIN '.$fulldump_timestamp_table.' AS b '.
                   2489:         'ON a.symb_id=b.symb_id AND a.student_id=b.student_id AND '.
                   2490:         'a.transaction = b.transaction '.
                   2491:         'LEFT JOIN '.$student_table.' as d '.
                   2492:         'ON a.student_id=d.student_id '.
1.106     matthew  2493:         'WHERE '.
1.107     matthew  2494:         'a.symb_id='.$symb_id.' AND a.part_id='.$part_id;
1.142     matthew  2495:     if (defined($student_requirements) || defined($enrollment_requirements)) {
                   2496:         $request .= ' AND ';
                   2497:         if (defined($student_requirements)) {
                   2498:             $request .= $student_requirements.' AND ';
                   2499:         }
                   2500:         if (defined($enrollment_requirements)) {
                   2501:             $request .= $enrollment_requirements.' AND ';
                   2502:         }
                   2503:         $request =~ s/( AND )$//;
1.106     matthew  2504:     }
                   2505:     $request .= ' ORDER BY b.timestamp';
                   2506: #    &Apache::lonnet::logthis("request =\n".$request);
                   2507:     my $sth = $dbh->prepare($request);
                   2508:     $sth->execute();
                   2509:     if ($dbh->err) {
1.138     matthew  2510:         &Apache::lonnet::logthis('error 5 = '.$dbh->errstr());
                   2511:         &Apache::lonnet::logthis('prepared then executed '.$/.$request);
1.106     matthew  2512:         return undef;
                   2513:     }
                   2514:     my $dataset = $sth->fetchall_arrayref();
                   2515:     if (ref($dataset) eq 'ARRAY' && scalar(@$dataset)>0) {
                   2516:         return $dataset;
                   2517:     }
                   2518: 
1.100     matthew  2519: }
1.61      matthew  2520: 
                   2521: ################################################
                   2522: ################################################
                   2523: 
                   2524: =pod
                   2525: 
1.116     matthew  2526: =item &get_student_scores($Sections,$Symbs,$enrollment,$courseid)
1.113     matthew  2527: 
                   2528: =cut
                   2529: 
                   2530: ################################################
                   2531: ################################################
                   2532: sub get_student_scores {
1.145     matthew  2533:     my ($sections,$Symbs,$enrollment,$courseid,$starttime,$endtime) = @_;
1.146     albertel 2534:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.113     matthew  2535:     &setup_table_names($courseid);
                   2536:     my $dbh = &Apache::lonmysql::get_dbh();
                   2537:     return (undef) if (! defined($dbh));
                   2538:     my $tmptable = $courseid.'_temp_'.time;
1.145     matthew  2539:     my $request = 'DROP TABLE IF EXISTS '.$tmptable;
                   2540: #    &Apache::lonnet::logthis('request = '.$/.$request);
                   2541:     $dbh->do($request);
1.114     matthew  2542:     #
                   2543:     my $symb_requirements;
1.113     matthew  2544:     if (defined($Symbs)  && @$Symbs) {
                   2545:         $symb_requirements = '('.
1.114     matthew  2546:             join(' OR ', map{ "(a.symb_id='".&get_symb_id($_->{'symb'}).
1.121     matthew  2547:                               "' AND a.part_id='".&get_part_id($_->{'part'}).
                   2548:                               "')"
1.113     matthew  2549:                               } @$Symbs).')';
                   2550:     }
1.114     matthew  2551:     #
1.145     matthew  2552:     my ($student_requirements,$enrollment_requirements) = 
                   2553:         &limit_by_section_and_status($sections,$enrollment,'b');
1.114     matthew  2554:     #
1.145     matthew  2555:     my $time_requirements = &limit_by_start_end_time($starttime,$endtime,'a');
1.114     matthew  2556:     ##
1.145     matthew  2557:     $request = 'CREATE TEMPORARY TABLE IF NOT EXISTS '.$tmptable.
                   2558:         ' SELECT a.student_id,SUM(a.awarded*c.weight) AS score FROM '.
1.114     matthew  2559:         $performance_table.' AS a ';
1.145     matthew  2560:     $request .= "LEFT JOIN ".$weight_table.' AS c ON a.symb_id=c.symb_id AND a.part_id=c.part_id ';
1.114     matthew  2561:     if (defined($student_requirements) || defined($enrollment_requirements)) {
1.145     matthew  2562:         $request .= ' LEFT JOIN '.$student_table.' AS b ON a.student_id=b.student_id';
1.114     matthew  2563:     }
                   2564:     if (defined($symb_requirements)      || 
                   2565:         defined($student_requirements)   ||
                   2566:         defined($enrollment_requirements) ) {
1.113     matthew  2567:         $request .= ' WHERE ';
                   2568:     }
1.114     matthew  2569:     if (defined($symb_requirements)) {
                   2570:         $request .= $symb_requirements.' AND ';
                   2571:     }
                   2572:     if (defined($student_requirements)) {
                   2573:         $request .= $student_requirements.' AND ';
                   2574:     }
                   2575:     if (defined($enrollment_requirements)) {
                   2576:         $request .= $enrollment_requirements.' AND ';
                   2577:     }
1.121     matthew  2578:     if (defined($time_requirements)) {
                   2579:         $request .= $time_requirements.' AND ';
                   2580:     }
                   2581:     $request =~ s/ AND $//; # Strip of the trailing ' AND '.
1.114     matthew  2582:     $request .= ' GROUP BY a.student_id';
                   2583: #    &Apache::lonnet::logthis("request = \n".$request);
1.113     matthew  2584:     my $sth = $dbh->prepare($request);
                   2585:     $sth->execute();
                   2586:     if ($dbh->err) {
1.138     matthew  2587:         &Apache::lonnet::logthis('error 6 = '.$dbh->errstr());
                   2588:         &Apache::lonnet::logthis('prepared then executed '.$/.$request);
1.113     matthew  2589:         return undef;
                   2590:     }
                   2591:     $request = 'SELECT score,COUNT(*) FROM '.$tmptable.' GROUP BY score';
                   2592: #    &Apache::lonnet::logthis("request = \n".$request);
                   2593:     $sth = $dbh->prepare($request);
                   2594:     $sth->execute();
                   2595:     if ($dbh->err) {
1.138     matthew  2596:         &Apache::lonnet::logthis('error 7 = '.$dbh->errstr());
                   2597:         &Apache::lonnet::logthis('prepared then executed '.$/.$request);
1.113     matthew  2598:         return undef;
                   2599:     }
                   2600:     my $dataset = $sth->fetchall_arrayref();
                   2601:     return $dataset;
                   2602: }
                   2603: 
                   2604: ################################################
                   2605: ################################################
                   2606: 
                   2607: =pod
                   2608: 
1.61      matthew  2609: =item &setup_table_names()
                   2610: 
                   2611: input: course id
                   2612: 
                   2613: output: none
                   2614: 
                   2615: Cleans up the package variables for local caching.
                   2616: 
                   2617: =cut
                   2618: 
                   2619: ################################################
                   2620: ################################################
                   2621: sub setup_table_names {
                   2622:     my ($courseid) = @_;
                   2623:     if (! defined($courseid)) {
1.146     albertel 2624:         $courseid = $env{'request.course.id'};
1.61      matthew  2625:     }
                   2626:     #
                   2627:     if (! defined($current_course) || $current_course ne $courseid) {
                   2628:         # Clear out variables
                   2629:         $have_read_part_table = 0;
                   2630:         undef(%ids_by_part);
                   2631:         undef(%parts_by_id);
                   2632:         $have_read_symb_table = 0;
                   2633:         undef(%ids_by_symb);
                   2634:         undef(%symbs_by_id);
                   2635:         $have_read_student_table = 0;
                   2636:         undef(%ids_by_student);
                   2637:         undef(%students_by_id);
                   2638:         #
                   2639:         $current_course = $courseid;
                   2640:     }
                   2641:     #
                   2642:     # Set up database names
                   2643:     my $base_id = $courseid;
                   2644:     $symb_table        = $base_id.'_'.'symb';
                   2645:     $part_table        = $base_id.'_'.'part';
                   2646:     $student_table     = $base_id.'_'.'student';
                   2647:     $performance_table = $base_id.'_'.'performance';
                   2648:     $parameters_table  = $base_id.'_'.'parameters';
1.89      matthew  2649:     $fulldump_part_table      = $base_id.'_'.'partdata';
                   2650:     $fulldump_response_table  = $base_id.'_'.'responsedata';
                   2651:     $fulldump_timestamp_table = $base_id.'_'.'timestampdata';
1.127     matthew  2652:     $weight_table             = $base_id.'_'.'weight';
1.89      matthew  2653:     #
                   2654:     @Tables = (
                   2655:                $symb_table,
                   2656:                $part_table,
                   2657:                $student_table,
                   2658:                $performance_table,
                   2659:                $parameters_table,
                   2660:                $fulldump_part_table,
                   2661:                $fulldump_response_table,
                   2662:                $fulldump_timestamp_table,
1.127     matthew  2663:                $weight_table,
1.89      matthew  2664:                );
1.61      matthew  2665:     return;
1.3       stredwic 2666: }
1.1       stredwic 2667: 
1.35      matthew  2668: ################################################
                   2669: ################################################
                   2670: 
                   2671: =pod
                   2672: 
1.57      matthew  2673: =back
                   2674: 
                   2675: =item End of Local Data Caching Subroutines
                   2676: 
                   2677: =cut
                   2678: 
                   2679: ################################################
                   2680: ################################################
                   2681: 
1.89      matthew  2682: } # End scope of table identifiers
1.57      matthew  2683: 
                   2684: ################################################
                   2685: ################################################
                   2686: 
                   2687: =pod
                   2688: 
                   2689: =head3 Classlist Subroutines
                   2690: 
1.35      matthew  2691: =item &get_classlist();
                   2692: 
                   2693: Retrieve the classist of a given class or of the current class.  Student
                   2694: information is returned from the classlist.db file and, if needed,
                   2695: from the students environment.
                   2696: 
1.150     albertel 2697: Optional arguments are $cdom, and $cnum (course domain,
                   2698: and course number, respectively).  If either is ommitted the course
                   2699: will be taken from the current environment ($env{'request.course.id'},
1.146     albertel 2700: $env{'course.'.$cid.'.domain'}, and $env{'course.'.$cid.'.num'}).
1.35      matthew  2701: 
                   2702: Returns a reference to a hash which contains:
                   2703:  keys    '$sname:$sdom'
1.136     raeburn  2704:  values  [$sdom,$sname,$end,$start,$id,$section,$fullname,$status,$type,$lockedtype]
1.54      bowersj2 2705: 
                   2706: The constant values CL_SDOM, CL_SNAME, CL_END, etc. can be used
                   2707: as indices into the returned list to future-proof clients against
                   2708: changes in the list order.
1.35      matthew  2709: 
                   2710: =cut
                   2711: 
                   2712: ################################################
                   2713: ################################################
1.54      bowersj2 2714: 
                   2715: sub CL_SDOM     { return 0; }
                   2716: sub CL_SNAME    { return 1; }
                   2717: sub CL_END      { return 2; }
                   2718: sub CL_START    { return 3; }
                   2719: sub CL_ID       { return 4; }
                   2720: sub CL_SECTION  { return 5; }
                   2721: sub CL_FULLNAME { return 6; }
                   2722: sub CL_STATUS   { return 7; }
1.111     raeburn  2723: sub CL_TYPE     { return 8; }
1.136     raeburn  2724: sub CL_LOCKEDTYPE   { return 9; }
1.35      matthew  2725: 
                   2726: sub get_classlist {
1.150     albertel 2727:     my ($cdom,$cnum) = @_;
                   2728:     my $cid = $cdom.'_'.$cnum;
                   2729:     if (!defined($cdom) || !defined($cnum)) {
                   2730: 	$cid =  $env{'request.course.id'};
                   2731: 	$cdom = $env{'course.'.$cid.'.domain'};
                   2732: 	$cnum = $env{'course.'.$cid.'.num'};
                   2733:     }
1.57      matthew  2734:     my $now = time;
1.35      matthew  2735:     #
                   2736:     my %classlist=&Apache::lonnet::dump('classlist',$cdom,$cnum);
                   2737:     while (my ($student,$info) = each(%classlist)) {
1.60      matthew  2738:         if ($student =~ /^(con_lost|error|no_such_host)/i) {
                   2739:             &Apache::lonnet::logthis('get_classlist error for '.$cid.':'.$student);
                   2740:             return undef;
                   2741:         }
1.35      matthew  2742:         my ($sname,$sdom) = split(/:/,$student);
                   2743:         my @Values = split(/:/,$info);
1.136     raeburn  2744:         my ($end,$start,$id,$section,$fullname,$type,$lockedtype);
1.35      matthew  2745:         if (@Values > 2) {
1.136     raeburn  2746:             ($end,$start,$id,$section,$fullname,$type,$lockedtype) = @Values;
1.35      matthew  2747:         } else { # We have to get the data ourselves
                   2748:             ($end,$start) = @Values;
1.37      matthew  2749:             $section = &Apache::lonnet::getsection($sdom,$sname,$cid);
1.35      matthew  2750:             my %info=&Apache::lonnet::get('environment',
                   2751:                                           ['firstname','middlename',
                   2752:                                            'lastname','generation','id'],
                   2753:                                           $sdom, $sname);
                   2754:             my ($tmp) = keys(%info);
                   2755:             if ($tmp =~/^(con_lost|error|no_such_host)/i) {
                   2756:                 $fullname = 'not available';
                   2757:                 $id = 'not available';
1.38      matthew  2758:                 &Apache::lonnet::logthis('unable to retrieve environment '.
                   2759:                                          'for '.$sname.':'.$sdom);
1.35      matthew  2760:             } else {
1.141     albertel 2761:                 $fullname = &Apache::lonnet::format_name(@info{qw/firstname middlename lastname generation/},'lastname');
1.35      matthew  2762:                 $id = $info{'id'};
                   2763:             }
1.36      matthew  2764:             # Update the classlist with this students information
                   2765:             if ($fullname ne 'not available') {
1.141     albertel 2766: 		my $enrolldata = join(':',$end,$start,$id,$section,$fullname);
                   2767: 		my $reply=&Apache::lonnet::cput('classlist',
1.36      matthew  2768:                                                 {$student => $enrolldata},
                   2769:                                                 $cdom,$cnum);
                   2770:                 if ($reply !~ /^(ok|delayed)/) {
                   2771:                     &Apache::lonnet::logthis('Unable to update classlist for '.
                   2772:                                              'student '.$sname.':'.$sdom.
                   2773:                                              ' error:'.$reply);
                   2774:                 }
                   2775:             }
1.35      matthew  2776:         }
                   2777:         my $status='Expired';
                   2778:         if(((!$end) || $now < $end) && ((!$start) || ($now > $start))) {
                   2779:             $status='Active';
                   2780:         }
                   2781:         $classlist{$student} = 
1.136     raeburn  2782:             [$sdom,$sname,$end,$start,$id,$section,$fullname,$status,$type,$lockedtype];
1.35      matthew  2783:     }
                   2784:     if (wantarray()) {
                   2785:         return (\%classlist,['domain','username','end','start','id',
1.136     raeburn  2786:                              'section','fullname','status','type','lockedtype']);
1.35      matthew  2787:     } else {
                   2788:         return \%classlist;
                   2789:     }
                   2790: }
                   2791: 
1.1       stredwic 2792: # ----- END HELPER FUNCTIONS --------------------------------------------
                   2793: 
                   2794: 1;
                   2795: __END__
1.36      matthew  2796: 
1.35      matthew  2797: 

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