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

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

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