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

1.1       stredwic    1: # The LearningOnline Network with CAPA
                      2: #
1.175   ! albertel    3: # $Id: loncoursedata.pm,v 1.174 2006/08/08 19:02:04 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;
                   1430:     my @tmp = &Apache::lonnet::currentdump($courseid,$sdom,$sname);
                   1431:     if ((scalar(@tmp) > 0) && ($tmp[0] =~ /^error:/)) {
                   1432:         &Apache::lonnet::logthis('error getting data for '.
                   1433:                                  $sname.':'.$sdom.' in course '.$courseid.
                   1434:                                  ':'.$tmp[0]);
                   1435:         $returnstatus = 'error getting data';
1.79      matthew  1436:         return ($returnstatus,undef);
1.57      matthew  1437:     }
                   1438:     if (scalar(@tmp) < 1) {
                   1439:         return ('no data',undef);
                   1440:     }
                   1441:     my %student_data = @tmp;
1.89      matthew  1442:     my @Results = &store_student_data($sname,$sdom,$courseid,\%student_data);
                   1443:     #
                   1444:     # Set the students update time
1.96      matthew  1445:     if ($Results[0] eq 'okay') {
1.148     matthew  1446:         &store_updatetime($student_id,$time_of_retrieval);
1.95      matthew  1447:     }
1.89      matthew  1448:     #
                   1449:     return @Results;
                   1450: }
                   1451: 
1.113     matthew  1452: sub store_updatetime {
                   1453:     my ($student_id,$updatetime,$fullupdatetime)=@_;
                   1454:     my $values = '';
                   1455:     if (defined($updatetime)) {
                   1456:         $values = 'updatetime='.$updatetime.' ';
                   1457:     }
                   1458:     if (defined($fullupdatetime)) {
                   1459:         if ($values ne '') {
                   1460:             $values .= ',';
                   1461:         }
                   1462:         $values .= 'fullupdatetime='.$fullupdatetime.' ';
                   1463:     }
                   1464:     return if ($values eq '');
                   1465:     my $dbh = &Apache::lonmysql::get_dbh();
                   1466:     my $request = 'UPDATE '.$student_table.' SET '.$values.
                   1467:         ' WHERE student_id='.$student_id.' LIMIT 1';
                   1468:     $dbh->do($request);
                   1469: }
                   1470: 
1.89      matthew  1471: sub store_student_data {
                   1472:     my ($sname,$sdom,$courseid,$student_data) = @_;
                   1473:     #
                   1474:     my $student_id = &get_student_id($sname,$sdom);
                   1475:     my $student = $sname.':'.$sdom;
                   1476:     #
                   1477:     my $returnstatus = 'okay';
1.57      matthew  1478:     #
                   1479:     # Remove all of the students data from the table
1.60      matthew  1480:     my $dbh = &Apache::lonmysql::get_dbh();
                   1481:     $dbh->do('DELETE FROM '.$performance_table.' WHERE student_id='.
                   1482:              $student_id);
                   1483:     $dbh->do('DELETE FROM '.$parameters_table.' WHERE student_id='.
                   1484:              $student_id);
1.57      matthew  1485:     #
                   1486:     # Store away the data
                   1487:     #
                   1488:     my $starttime = Time::HiRes::time;
                   1489:     my $elapsed = 0;
                   1490:     my $rows_stored;
1.98      matthew  1491:     my $store_parameters_command  = 'INSERT IGNORE INTO '.$parameters_table.
1.60      matthew  1492:         ' VALUES '."\n";
1.61      matthew  1493:     my $num_parameters = 0;
1.98      matthew  1494:     my $store_performance_command = 'INSERT IGNORE INTO '.$performance_table.
1.60      matthew  1495:         ' VALUES '."\n";
1.79      matthew  1496:     return ('error',undef) if (! defined($dbh));
1.89      matthew  1497:     while (my ($current_symb,$param_hash) = each(%{$student_data})) {
1.57      matthew  1498:         #
                   1499:         # make sure the symb is set up properly
                   1500:         my $symb_id = &get_symb_id($current_symb);
                   1501:         #
1.147     matthew  1502:         # Parameters
1.63      matthew  1503:         while (my ($parameter,$value) = each(%$param_hash)) {
                   1504:             if ($parameter !~ /(timestamp|resource\.(.*)\.(solved|tries|awarded|award|awarddetail|previous))/) {
1.147     matthew  1505:                 my $sql_parameter = "('".join("','",
                   1506:                                               $symb_id,$student_id,
                   1507:                                               $parameter)."',".
                   1508:                                                   $dbh->quote($value)."),\n";
1.61      matthew  1509:                 $num_parameters ++;
1.147     matthew  1510:                 if ($sql_parameter !~ /''/) {
                   1511:                     $store_parameters_command .= $sql_parameter;
1.149     albertel 1512:                     #$rows_stored++;
1.57      matthew  1513:                 }
                   1514:             }
1.147     matthew  1515:         }
                   1516:         # Performance
                   1517:         my %stored;
                   1518:         while (my ($parameter,$value) = each(%$param_hash)) {
                   1519:             next if ($parameter !~ /^resource\.(.*)\.(solved|awarded)$/);
1.161     albertel 1520:             my $part  = $1;
                   1521: 	    my $which = $2;
1.151     albertel 1522: 	    next if ($part =~ /\./);
1.147     matthew  1523:             next if (exists($stored{$part}));
                   1524:             $stored{$part}++;
1.57      matthew  1525:             #
                   1526:             my $part_id = &get_part_id($part);
                   1527:             next if (!defined($part_id));
1.161     albertel 1528: 	    
                   1529:             my ($solved,$awarded);
                   1530: 	    if ($which eq 'solved') {
                   1531: 		$solved  = $value;
                   1532: 		$awarded = $param_hash->{'resource.'.$part.'.awarded'};
                   1533: 	    } else {
                   1534: 		$solved  = $param_hash->{'resource.'.$part.'.solved'};
                   1535: 		$awarded = $value;
                   1536: 	    }
1.57      matthew  1537:             my $award   = $param_hash->{'resource.'.$part.'.award'};
                   1538:             my $awarddetail = $param_hash->{'resource.'.$part.'.awarddetail'};
                   1539:             my $timestamp = $param_hash->{'timestamp'};
1.164     albertel 1540: 	    my $tries   = $param_hash->{'resource.'.$part.'.tries'};
                   1541: 	    if (&symb_is_for_task($current_symb)) {
                   1542: 		$tries   = $param_hash->{'resource.'.$part.'.version'};
                   1543: 	    }
1.60      matthew  1544:             #
1.74      matthew  1545:             $solved      = '' if (! defined($solved));
1.57      matthew  1546:             $tries       = '' if (! defined($tries));
                   1547:             $awarded     = '' if (! defined($awarded));
                   1548:             $award       = '' if (! defined($award));
                   1549:             $awarddetail = '' if (! defined($awarddetail));
1.147     matthew  1550:             my $sql_performance = 
                   1551:                 "('".join("','",$symb_id,$student_id,$part_id,$part,
                   1552:                                 $solved,$tries,$awarded,$award,
                   1553:                                 $awarddetail,$timestamp)."'),\n";
                   1554:             $store_performance_command .= $sql_performance;
1.57      matthew  1555:             $rows_stored++;
                   1556:         }
                   1557:     }
1.149     albertel 1558:     if (! $rows_stored) { return ($returnstatus, undef); }
1.147     matthew  1559:     $store_parameters_command =~ s|,\n$||;
                   1560:     $store_performance_command =~ s|,\n$||;
1.57      matthew  1561:     my $start = Time::HiRes::time;
1.94      matthew  1562:     $dbh->do($store_performance_command);
                   1563:     if ($dbh->err()) {
1.147     matthew  1564:         &Apache::lonnet::logthis('performance bigass insert error:'.
                   1565:                                  $dbh->errstr());
                   1566:         &Apache::lonnet::logthis('command = '.$/.$store_performance_command);
1.94      matthew  1567:         $returnstatus = 'error: unable to insert performance into database';
                   1568:         return ($returnstatus,$student_data);
                   1569:     }
1.61      matthew  1570:     $dbh->do($store_parameters_command) if ($num_parameters>0);
1.57      matthew  1571:     if ($dbh->err()) {
1.147     matthew  1572:         &Apache::lonnet::logthis('parameters bigass insert error:'.
                   1573:                                  $dbh->errstr());
                   1574:         &Apache::lonnet::logthis('command = '.$/.$store_parameters_command);
1.87      matthew  1575:         &Apache::lonnet::logthis('rows_stored = '.$rows_stored);
                   1576:         &Apache::lonnet::logthis('student_id = '.$student_id);
1.57      matthew  1577:         $returnstatus = 'error: unable to insert parameters into database';
1.89      matthew  1578:         return ($returnstatus,$student_data);
1.57      matthew  1579:     }
                   1580:     $elapsed += Time::HiRes::time - $start;
1.89      matthew  1581:     return ($returnstatus,$student_data);
1.57      matthew  1582: }
                   1583: 
1.89      matthew  1584: ######################################
                   1585: ######################################
1.57      matthew  1586: 
                   1587: =pod
                   1588: 
1.89      matthew  1589: =item &ensure_tables_are_set_up($courseid)
1.57      matthew  1590: 
1.89      matthew  1591: Checks to be sure the MySQL tables for the given class are set up.
                   1592: If $courseid is omitted it will be obtained from the environment.
1.57      matthew  1593: 
1.89      matthew  1594: Returns nothing on success and 'error' on failure
1.57      matthew  1595: 
                   1596: =cut
                   1597: 
1.89      matthew  1598: ######################################
                   1599: ######################################
                   1600: sub ensure_tables_are_set_up {
                   1601:     my ($courseid) = @_;
1.146     albertel 1602:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.61      matthew  1603:     # 
                   1604:     # Clean out package variables
1.57      matthew  1605:     &setup_table_names($courseid);
                   1606:     #
                   1607:     # if the tables do not exist, make them
                   1608:     my @CurrentTable = &Apache::lonmysql::tables_in_db();
1.167     raeburn  1609:     my ($found_symb,$found_student,$found_groups,$found_groupnames,$found_part,
1.89      matthew  1610:         $found_performance,$found_parameters,$found_fulldump_part,
1.127     matthew  1611:         $found_fulldump_response,$found_fulldump_timestamp,
                   1612:         $found_weight);
1.57      matthew  1613:     foreach (@CurrentTable) {
                   1614:         $found_symb        = 1 if ($_ eq $symb_table);
                   1615:         $found_student     = 1 if ($_ eq $student_table);
1.167     raeburn  1616:         $found_groups      = 1 if ($_ eq $students_groups_table);
                   1617:         $found_groupnames  = 1 if ($_ eq $groupnames_table);
1.57      matthew  1618:         $found_part        = 1 if ($_ eq $part_table);
                   1619:         $found_performance = 1 if ($_ eq $performance_table);
                   1620:         $found_parameters  = 1 if ($_ eq $parameters_table);
1.89      matthew  1621:         $found_fulldump_part      = 1 if ($_ eq $fulldump_part_table);
                   1622:         $found_fulldump_response  = 1 if ($_ eq $fulldump_response_table);
                   1623:         $found_fulldump_timestamp = 1 if ($_ eq $fulldump_timestamp_table);
1.127     matthew  1624:         $found_weight      = 1 if ($_ eq $weight_table);
1.57      matthew  1625:     }
1.127     matthew  1626:     if (!$found_symb          || 
                   1627:         !$found_student       || !$found_part              ||
                   1628:         !$found_performance   || !$found_parameters        ||
1.89      matthew  1629:         !$found_fulldump_part || !$found_fulldump_response ||
1.127     matthew  1630:         !$found_fulldump_timestamp || !$found_weight ) {
1.134     matthew  1631:         if (&init_dbs($courseid,1)) {
1.89      matthew  1632:             return 'error';
1.57      matthew  1633:         }
                   1634:     }
1.89      matthew  1635: }
                   1636: 
                   1637: ################################################
                   1638: ################################################
                   1639: 
                   1640: =pod
                   1641: 
                   1642: =item &ensure_current_data()
                   1643: 
                   1644: Input: $sname, $sdom, $courseid
                   1645: 
                   1646: Output: $status, $data
                   1647: 
                   1648: This routine ensures the data for a given student is up to date.
1.113     matthew  1649: The $student_table is queried to determine the time of the last update.  
1.89      matthew  1650: If the students data is out of date, &update_student_data() is called.  
                   1651: The return values from the call to &update_student_data() are returned.
                   1652: 
                   1653: =cut
                   1654: 
                   1655: ################################################
                   1656: ################################################
                   1657: sub ensure_current_data {
                   1658:     my ($sname,$sdom,$courseid) = @_;
                   1659:     my $status = 'okay';   # return value
                   1660:     #
1.146     albertel 1661:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.89      matthew  1662:     &ensure_tables_are_set_up($courseid);
1.57      matthew  1663:     #
                   1664:     # Get the update time for the user
                   1665:     my $updatetime = 0;
1.60      matthew  1666:     my $modifiedtime = &Apache::lonnet::GetFileTimestamp
                   1667:         ($sdom,$sname,$courseid.'.db',
                   1668:          $Apache::lonnet::perlvar{'lonUsersDir'});
1.57      matthew  1669:     #
1.87      matthew  1670:     my $student_id = &get_student_id($sname,$sdom);
1.113     matthew  1671:     my @Result = &Apache::lonmysql::get_rows($student_table,
1.87      matthew  1672:                                              "student_id ='$student_id'");
1.57      matthew  1673:     my $data = undef;
                   1674:     if (@Result) {
1.113     matthew  1675:         $updatetime = $Result[0]->[5];  # Ack!  This is dumb!
1.57      matthew  1676:     }
                   1677:     if ($modifiedtime > $updatetime) {
                   1678:         ($status,$data) = &update_student_data($sname,$sdom,$courseid);
                   1679:     }
                   1680:     return ($status,$data);
                   1681: }
                   1682: 
                   1683: ################################################
                   1684: ################################################
                   1685: 
                   1686: =pod
                   1687: 
1.89      matthew  1688: =item &ensure_current_full_data($sname,$sdom,$courseid)
                   1689: 
                   1690: Input: $sname, $sdom, $courseid
                   1691: 
                   1692: Output: $status
                   1693: 
                   1694: This routine ensures the fulldata (the data from a lonnet::dump, not a
                   1695: lonnet::currentdump) for a given student is up to date.
1.113     matthew  1696: The $student_table is queried to determine the time of the last update.  
1.89      matthew  1697: If the students fulldata is out of date, &update_full_student_data() is
                   1698: called.  
                   1699: 
                   1700: The return value from the call to &update_full_student_data() is returned.
                   1701: 
                   1702: =cut
                   1703: 
                   1704: ################################################
                   1705: ################################################
                   1706: sub ensure_current_full_data {
                   1707:     my ($sname,$sdom,$courseid) = @_;
                   1708:     my $status = 'okay';   # return value
                   1709:     #
1.146     albertel 1710:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.89      matthew  1711:     &ensure_tables_are_set_up($courseid);
                   1712:     #
                   1713:     # Get the update time for the user
                   1714:     my $modifiedtime = &Apache::lonnet::GetFileTimestamp
                   1715:         ($sdom,$sname,$courseid.'.db',
                   1716:          $Apache::lonnet::perlvar{'lonUsersDir'});
                   1717:     #
                   1718:     my $student_id = &get_student_id($sname,$sdom);
1.113     matthew  1719:     my @Result = &Apache::lonmysql::get_rows($student_table,
1.89      matthew  1720:                                              "student_id ='$student_id'");
                   1721:     my $updatetime;
                   1722:     if (@Result && ref($Result[0]) eq 'ARRAY') {
1.113     matthew  1723:         $updatetime = $Result[0]->[6];
1.89      matthew  1724:     }
                   1725:     if (! defined($updatetime) || $modifiedtime > $updatetime) {
                   1726:         $status = &update_full_student_data($sname,$sdom,$courseid);
                   1727:     }
                   1728:     return $status;
                   1729: }
                   1730: 
                   1731: ################################################
                   1732: ################################################
                   1733: 
                   1734: =pod
                   1735: 
1.57      matthew  1736: =item &get_student_data_from_performance_cache()
                   1737: 
                   1738: Input: $sname, $sdom, $symb, $courseid
                   1739: 
                   1740: Output: hash reference containing the data for the given student.
                   1741: If $symb is undef, all the students data is returned.
                   1742: 
                   1743: This routine is the heart of the local caching system.  See the description
                   1744: of $performance_table, $symb_table, $student_table, and $part_table.  The
                   1745: main task is building the MySQL request.  The tables appear in the request
                   1746: in the order in which they should be parsed by MySQL.  When searching
                   1747: on a student the $student_table is used to locate the 'student_id'.  All
                   1748: rows in $performance_table which have a matching 'student_id' are returned,
                   1749: with data from $part_table and $symb_table which match the entries in
                   1750: $performance_table, 'part_id' and 'symb_id'.  When searching on a symb,
                   1751: the $symb_table is processed first, with matching rows grabbed from 
                   1752: $performance_table and filled in from $part_table and $student_table in
                   1753: that order.  
                   1754: 
                   1755: Running 'EXPLAIN ' on the 'SELECT' statements generated can be quite 
                   1756: interesting, especially if you play with the order the tables are listed.  
                   1757: 
                   1758: =cut
                   1759: 
                   1760: ################################################
                   1761: ################################################
                   1762: sub get_student_data_from_performance_cache {
                   1763:     my ($sname,$sdom,$symb,$courseid)=@_;
                   1764:     my $student = $sname.':'.$sdom if (defined($sname) && defined($sdom));
1.61      matthew  1765:     &setup_table_names($courseid);
1.57      matthew  1766:     #
                   1767:     # Return hash
                   1768:     my $studentdata;
                   1769:     #
                   1770:     my $dbh = &Apache::lonmysql::get_dbh();
                   1771:     my $request = "SELECT ".
1.73      matthew  1772:         "d.symb,a.part,a.solved,a.tries,a.awarded,a.award,a.awarddetail,".
1.63      matthew  1773:             "a.timestamp ";
1.57      matthew  1774:     if (defined($student)) {
                   1775:         $request .= "FROM $student_table AS b ".
                   1776:             "LEFT JOIN $performance_table AS a ON b.student_id=a.student_id ".
1.73      matthew  1777: #            "LEFT JOIN $part_table AS c ON c.part_id = a.part_id ".
1.57      matthew  1778:             "LEFT JOIN $symb_table AS d ON d.symb_id = a.symb_id ".
                   1779:                 "WHERE student='$student'";
                   1780:         if (defined($symb) && $symb ne '') {
1.67      matthew  1781:             $request .= " AND d.symb=".$dbh->quote($symb);
1.57      matthew  1782:         }
                   1783:     } elsif (defined($symb) && $symb ne '') {
                   1784:         $request .= "FROM $symb_table as d ".
                   1785:             "LEFT JOIN $performance_table AS a ON d.symb_id=a.symb_id ".
1.73      matthew  1786: #            "LEFT JOIN $part_table    AS c ON c.part_id = a.part_id ".
1.57      matthew  1787:             "LEFT JOIN $student_table AS b ON b.student_id = a.student_id ".
                   1788:                 "WHERE symb='".$dbh->quote($symb)."'";
                   1789:     }
                   1790:     my $starttime = Time::HiRes::time;
                   1791:     my $rows_retrieved = 0;
                   1792:     my $sth = $dbh->prepare($request);
                   1793:     $sth->execute();
                   1794:     if ($sth->err()) {
                   1795:         &Apache::lonnet::logthis("Unable to execute MySQL request:");
                   1796:         &Apache::lonnet::logthis("\n".$request."\n");
                   1797:         &Apache::lonnet::logthis("error is:".$sth->errstr());
                   1798:         return undef;
                   1799:     }
                   1800:     foreach my $row (@{$sth->fetchall_arrayref}) {
                   1801:         $rows_retrieved++;
1.63      matthew  1802:         my ($symb,$part,$solved,$tries,$awarded,$award,$awarddetail,$time) = 
1.57      matthew  1803:             (@$row);
                   1804:         my $base = 'resource.'.$part;
                   1805:         $studentdata->{$symb}->{$base.'.solved'}  = $solved;
                   1806:         $studentdata->{$symb}->{$base.'.tries'}   = $tries;
                   1807:         $studentdata->{$symb}->{$base.'.awarded'} = $awarded;
                   1808:         $studentdata->{$symb}->{$base.'.award'}   = $award;
                   1809:         $studentdata->{$symb}->{$base.'.awarddetail'} = $awarddetail;
                   1810:         $studentdata->{$symb}->{'timestamp'} = $time if (defined($time) && $time ne '');
1.67      matthew  1811:     }
1.97      matthew  1812:     ## Get misc parameters
                   1813:     $request = 'SELECT c.symb,a.parameter,a.value '.
                   1814:         "FROM $student_table AS b ".
                   1815:         "LEFT JOIN $parameters_table AS a ON b.student_id=a.student_id ".
                   1816:         "LEFT JOIN $symb_table AS c ON c.symb_id = a.symb_id ".
                   1817:         "WHERE student='$student'";
                   1818:     if (defined($symb) && $symb ne '') {
                   1819:         $request .= " AND c.symb=".$dbh->quote($symb);
                   1820:     }
                   1821:     $sth = $dbh->prepare($request);
                   1822:     $sth->execute();
                   1823:     if ($sth->err()) {
                   1824:         &Apache::lonnet::logthis("Unable to execute MySQL request:");
                   1825:         &Apache::lonnet::logthis("\n".$request."\n");
                   1826:         &Apache::lonnet::logthis("error is:".$sth->errstr());
                   1827:         if (defined($symb) && $symb ne '') {
                   1828:             $studentdata = $studentdata->{$symb};
                   1829:         }
                   1830:         return $studentdata;
                   1831:     }
                   1832:     #
                   1833:     foreach my $row (@{$sth->fetchall_arrayref}) {
                   1834:         $rows_retrieved++;
                   1835:         my ($symb,$parameter,$value) = (@$row);
                   1836:         $studentdata->{$symb}->{$parameter}  = $value;
                   1837:     }
                   1838:     #
1.67      matthew  1839:     if (defined($symb) && $symb ne '') {
                   1840:         $studentdata = $studentdata->{$symb};
1.57      matthew  1841:     }
                   1842:     return $studentdata;
                   1843: }
                   1844: 
                   1845: ################################################
                   1846: ################################################
                   1847: 
                   1848: =pod
                   1849: 
                   1850: =item &get_current_state()
                   1851: 
                   1852: Input: $sname,$sdom,$symb,$courseid
                   1853: 
                   1854: Output: Described below
1.46      matthew  1855: 
1.47      matthew  1856: Retrieve the current status of a students performance.  $sname and
1.46      matthew  1857: $sdom are the only required parameters.  If $symb is undef the results
1.47      matthew  1858: of an &Apache::lonnet::currentdump() will be returned.  
1.46      matthew  1859: If $courseid is undef it will be retrieved from the environment.
                   1860: 
                   1861: The return structure is based on &Apache::lonnet::currentdump.  If
                   1862: $symb is unspecified, all the students data is returned in a hash of
                   1863: the form:
                   1864: ( 
                   1865:   symb1 => { param1 => value1, param2 => value2 ... },
                   1866:   symb2 => { param1 => value1, param2 => value2 ... },
                   1867: )
                   1868: 
                   1869: If $symb is specified, a hash of 
                   1870: (
                   1871:   param1 => value1, 
                   1872:   param2 => value2,
                   1873: )
                   1874: is returned.
                   1875: 
1.57      matthew  1876: If no data is found for $symb, or if the student has no performance data,
1.46      matthew  1877: an empty list is returned.
                   1878: 
                   1879: =cut
                   1880: 
                   1881: ################################################
                   1882: ################################################
                   1883: sub get_current_state {
1.47      matthew  1884:     my ($sname,$sdom,$symb,$courseid,$forcedownload)=@_;
                   1885:     #
1.146     albertel 1886:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.47      matthew  1887:     #
1.61      matthew  1888:     return () if (! defined($sname) || ! defined($sdom));
                   1889:     #
1.57      matthew  1890:     my ($status,$data) = &ensure_current_data($sname,$sdom,$courseid);
1.77      matthew  1891: #    &Apache::lonnet::logthis
                   1892: #        ('sname = '.$sname.
                   1893: #         ' domain = '.$sdom.
                   1894: #         ' status = '.$status.
                   1895: #         ' data is '.(defined($data)?'defined':'undefined'));
1.73      matthew  1896: #    while (my ($symb,$hash) = each(%$data)) {
                   1897: #        &Apache::lonnet::logthis($symb."\n----------------------------------");
                   1898: #        while (my ($key,$value) = each (%$hash)) {
                   1899: #            &Apache::lonnet::logthis("   ".$key." = ".$value);
                   1900: #        }
                   1901: #    }
1.47      matthew  1902:     #
1.79      matthew  1903:     if (defined($data) && defined($symb) && ref($data->{$symb})) {
                   1904:         return %{$data->{$symb}};
                   1905:     } elsif (defined($data) && ! defined($symb) && ref($data)) {
                   1906:         return %$data;
                   1907:     } 
                   1908:     if ($status eq 'no data') {
1.57      matthew  1909:         return ();
                   1910:     } else {
                   1911:         if ($status ne 'okay' && $status ne '') {
                   1912:             &Apache::lonnet::logthis('status = '.$status);
1.47      matthew  1913:             return ();
                   1914:         }
1.57      matthew  1915:         my $returnhash = &get_student_data_from_performance_cache($sname,$sdom,
                   1916:                                                       $symb,$courseid);
                   1917:         return %$returnhash if (defined($returnhash));
1.46      matthew  1918:     }
1.57      matthew  1919:     return ();
1.61      matthew  1920: }
                   1921: 
                   1922: ################################################
                   1923: ################################################
                   1924: 
                   1925: =pod
                   1926: 
                   1927: =item &get_problem_statistics()
                   1928: 
                   1929: Gather data on a given problem.  The database is assumed to be 
                   1930: populated and all local caching variables are assumed to be set
                   1931: properly.  This means you need to call &ensure_current_data for
                   1932: the students you are concerned with prior to calling this routine.
                   1933: 
1.167     raeburn  1934: Inputs: $Sections, Groups, $status, $symb, $part, $courseid, $starttime,
                   1935:         $endtime
1.61      matthew  1936: 
1.64      matthew  1937: =over 4
                   1938: 
1.124     matthew  1939: =item $Sections Array ref containing section names for students.  
                   1940: 'all' is allowed to be the first (and only) item in the array.
                   1941: 
1.167     raeburn  1942: =item $Groups Array ref containing group names for students.
                   1943: 'all' is allowed to be the first (and only) item in the array.
                   1944: 
1.124     matthew  1945: =item $status String describing the status of students
1.64      matthew  1946: 
                   1947: =item $symb is the symb for the problem.
                   1948: 
                   1949: =item $part is the part id you need statistics for
                   1950: 
                   1951: =item $courseid is the course id, of course!
                   1952: 
1.122     matthew  1953: =item $starttime and $endtime are unix times which to use to limit
                   1954: the statistical data.
                   1955: 
1.64      matthew  1956: =back
                   1957: 
1.66      matthew  1958: Outputs: See the code for up to date information.  A hash reference is
                   1959: returned.  The hash has the following keys defined:
1.64      matthew  1960: 
                   1961: =over 4
                   1962: 
1.66      matthew  1963: =item num_students The number of students attempting the problem
                   1964:       
                   1965: =item tries The total number of tries for the students
                   1966:       
                   1967: =item max_tries The maximum number of tries taken
                   1968:       
                   1969: =item mean_tries The average number of tries
                   1970:       
                   1971: =item num_solved The number of students able to solve the problem
                   1972:       
                   1973: =item num_override The number of students whose answer is 'correct_by_override'
                   1974:       
                   1975: =item deg_of_diff The degree of difficulty of the problem
                   1976:       
                   1977: =item std_tries The standard deviation of the number of tries
                   1978:       
                   1979: =item skew_tries The skew of the number of tries
1.64      matthew  1980: 
1.66      matthew  1981: =item per_wrong The number of students attempting the problem who were not
                   1982: able to answer it correctly.
1.64      matthew  1983: 
                   1984: =back
                   1985: 
1.61      matthew  1986: =cut
                   1987: 
                   1988: ################################################
                   1989: ################################################
                   1990: sub get_problem_statistics {
1.167     raeburn  1991:     my ($Sections,$Groups,$status,$symb,$part,$courseid,$starttime,$endtime) = @_;
1.61      matthew  1992:     return if (! defined($symb) || ! defined($part));
1.146     albertel 1993:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.61      matthew  1994:     #
1.100     matthew  1995:     &setup_table_names($courseid);
1.61      matthew  1996:     my $symb_id = &get_symb_id($symb);
                   1997:     my $part_id = &get_part_id($part);
                   1998:     my $stats_table = $courseid.'_problem_stats';
                   1999:     #
                   2000:     my $dbh = &Apache::lonmysql::get_dbh();
                   2001:     return undef if (! defined($dbh));
                   2002:     #
1.123     matthew  2003:     # Clean out the table
1.61      matthew  2004:     $dbh->do('DROP TABLE '.$stats_table);  # May return an error
                   2005:     my $request = 
1.115     matthew  2006:         'CREATE TEMPORARY TABLE '.$stats_table.' '.
                   2007:         'SELECT a.student_id,a.solved,a.award,a.awarded,a.tries '.
                   2008:         'FROM '.$performance_table.' AS a ';
1.123     matthew  2009:     #
                   2010:     # See if we need to include some requirements on the students
1.115     matthew  2011:     if ((defined($Sections) && lc($Sections->[0]) ne 'all') || 
                   2012:         (defined($status)   && lc($status)        ne 'any')) {
                   2013:         $request .= 'NATURAL LEFT JOIN '.$student_table.' AS b ';
                   2014:     }
1.167     raeburn  2015:     my ($groups_join,$group_limits) = &limit_by_group($Groups,'b','c','d');
                   2016:     if (defined($groups_join)) {
                   2017:         $request .= $groups_join;
                   2018:     }
1.115     matthew  2019:     $request .= ' WHERE a.symb_id='.$symb_id.' AND a.part_id='.$part_id;
1.123     matthew  2020:     #
                   2021:     # Limit the students included to those specified
1.115     matthew  2022:     if (defined($Sections) && lc($Sections->[0]) ne 'all') {
1.64      matthew  2023:         $request .= ' AND ('.
1.115     matthew  2024:             join(' OR ', map { "b.section='".$_."'" } @$Sections
1.64      matthew  2025:                  ).')';
                   2026:     }
1.115     matthew  2027:     if (defined($status) && lc($status) ne 'any') {
                   2028:         $request .= " AND b.status='".$status."'";
1.122     matthew  2029:     }
                   2030:     #
1.123     matthew  2031:     # Limit by starttime and endtime
1.122     matthew  2032:     my $time_requirements = undef;
                   2033:     if (defined($starttime)) {
                   2034:         $time_requirements .= 'a.timestamp>='.$starttime;
                   2035:         if (defined($endtime)) {
                   2036:             $time_requirements .= ' AND a.timestamp<='.$endtime;
                   2037:         }
                   2038:     } elsif (defined($endtime)) {
                   2039:         $time_requirements .= 'a.timestamp<='.$endtime;
                   2040:     }
                   2041:     if (defined($time_requirements)) {
                   2042:         $request .= ' AND '.$time_requirements;
1.115     matthew  2043:     }
1.167     raeburn  2044:     # Limit by group, as required
                   2045:     if (defined($group_limits)) {
                   2046:         $request .= ' AND '.$group_limits;
                   2047:     }
1.123     matthew  2048:     #
                   2049:     # Finally, execute the request to create the temporary table
1.61      matthew  2050:     $dbh->do($request);
1.123     matthew  2051:     #
                   2052:     # Collect the first suite of statistics
1.128     matthew  2053:     $request = 'SELECT COUNT(*),SUM(tries),'.
                   2054:         'AVG(tries),STD(tries) '.
1.109     matthew  2055:         'FROM '.$stats_table;
1.128     matthew  2056:     my ($num,$tries,$mean,$STD) = &execute_SQL_request
1.109     matthew  2057:         ($dbh,$request);
1.128     matthew  2058:     #
                   2059:     $request = 'SELECT MAX(tries),MIN(tries) FROM '.$stats_table.
                   2060:         ' WHERE awarded>0';
                   2061:     if (defined($time_requirements)) {
                   2062:         $request .= ' AND '.$time_requirements;
                   2063:     }
                   2064:     my ($max,$min) = &execute_SQL_request($dbh,$request);
                   2065:     #
1.109     matthew  2066:     $request = 'SELECT SUM(awarded) FROM '.$stats_table;
1.128     matthew  2067:     if (defined($time_requirements)) {
                   2068:         $request .= ' AND '.$time_requirements;
                   2069:     }
1.109     matthew  2070:     my ($Solved) = &execute_SQL_request($dbh,$request);
1.128     matthew  2071:     #
1.109     matthew  2072:     $request = 'SELECT SUM(awarded) FROM '.$stats_table.
                   2073:         " WHERE solved='correct_by_override'";
1.128     matthew  2074:     if (defined($time_requirements)) {
                   2075:         $request .= ' AND '.$time_requirements;
                   2076:     }
1.109     matthew  2077:     my ($solved) = &execute_SQL_request($dbh,$request);
                   2078:     #
1.133     matthew  2079:     $Solved -= $solved;
                   2080:     #
1.61      matthew  2081:     $num    = 0 if (! defined($num));
                   2082:     $tries  = 0 if (! defined($tries));
1.128     matthew  2083:     $max    = 0 if (! defined($max));
                   2084:     $min    = 0 if (! defined($min));
1.61      matthew  2085:     $STD    = 0 if (! defined($STD));
1.133     matthew  2086:     $Solved = 0 if (! defined($Solved) || $Solved < 0);
1.61      matthew  2087:     $solved = 0 if (! defined($solved));
                   2088:     #
1.123     matthew  2089:     # Compute the more complicated statistics
1.61      matthew  2090:     my $DegOfDiff = 'nan';
1.66      matthew  2091:     $DegOfDiff = 1-($Solved)/$tries if ($tries>0);
1.123     matthew  2092:     #
1.61      matthew  2093:     my $SKEW = 'nan';
1.66      matthew  2094:     my $wrongpercent = 0;
1.128     matthew  2095:     my $numwrong = 'nan';
1.61      matthew  2096:     if ($num > 0) {
                   2097:         ($SKEW) = &execute_SQL_request($dbh,'SELECT SQRT(SUM('.
                   2098:                                      'POWER(tries - '.$STD.',3)'.
                   2099:                                      '))/'.$num.' FROM '.$stats_table);
1.128     matthew  2100:         $numwrong = $num-$Solved;
                   2101:         $wrongpercent=int(10*100*$numwrong/$num)/10;
1.61      matthew  2102:     }
                   2103:     #
1.123     matthew  2104:     # Drop the temporary table
                   2105:     $dbh->do('DROP TABLE '.$stats_table);  # May return an error
1.81      matthew  2106:     #
                   2107:     # Return result
1.66      matthew  2108:     return { num_students => $num,
                   2109:              tries        => $tries,
1.128     matthew  2110:              max_tries    => $max,
                   2111:              min_tries    => $min,
1.66      matthew  2112:              mean_tries   => $mean,
                   2113:              std_tries    => $STD,
                   2114:              skew_tries   => $SKEW,
                   2115:              num_solved   => $Solved,
                   2116:              num_override => $solved,
1.128     matthew  2117:              num_wrong    => $numwrong,
1.66      matthew  2118:              per_wrong    => $wrongpercent,
1.81      matthew  2119:              deg_of_diff  => $DegOfDiff };
1.61      matthew  2120: }
                   2121: 
1.127     matthew  2122: ##
                   2123: ## This is a helper for get_statistics
1.61      matthew  2124: sub execute_SQL_request {
                   2125:     my ($dbh,$request)=@_;
                   2126: #    &Apache::lonnet::logthis($request);
                   2127:     my $sth = $dbh->prepare($request);
1.153     albertel 2128:     if (!$sth) {
                   2129: 	die($dbh->errstr . " SQL: $request");
                   2130:     }
1.61      matthew  2131:     $sth->execute();
                   2132:     my $row = $sth->fetchrow_arrayref();
                   2133:     if (ref($row) eq 'ARRAY' && scalar(@$row)>0) {
                   2134:         return @$row;
                   2135:     }
                   2136:     return ();
                   2137: }
1.123     matthew  2138: 
1.127     matthew  2139: ######################################################
                   2140: ######################################################
                   2141: 
                   2142: =pod
                   2143: 
                   2144: =item &populate_weight_table
                   2145: 
                   2146: =cut
                   2147: 
                   2148: ######################################################
                   2149: ######################################################
                   2150: sub populate_weight_table {
                   2151:     my ($courseid) = @_;
                   2152:     if (! defined($courseid)) {
1.146     albertel 2153:         $courseid = $env{'request.course.id'};
1.127     matthew  2154:     }
                   2155:     #
                   2156:     &setup_table_names($courseid);
1.144     matthew  2157:     my $navmap = Apache::lonnavmaps::navmap->new();
                   2158:     if (!defined($navmap)) {
                   2159:         &Apache::lonnet::logthis('loncoursedata::populate_weight_table:'.$/.
                   2160:                                  '  unable to get navmaps resource'.$/.
                   2161:                                  '  '.join(' ',(caller)));
                   2162:         return;
                   2163:     }
                   2164:     my @sequences = $navmap->retrieveResources(undef,
                   2165:                                                sub { shift->is_map(); },1,0,1);
                   2166:     my @resources;
                   2167:     foreach my $seq (@sequences) {
                   2168:         push(@resources,$navmap->retrieveResources($seq,
                   2169:                                                    sub {shift->is_problem();},
                   2170:                                                    0,0,0));
                   2171:     }
                   2172:     if (! scalar(@resources)) {
                   2173:         &Apache::lonnet::logthis('loncoursedata::populate_weight_table:'.$/.
                   2174:                                  ' no resources returned for '.$courseid);
1.127     matthew  2175:         return;
                   2176:     }
                   2177:     #       Since we use lonnet::EXT to retrieve problem weights,
                   2178:     #       to ensure current data we must clear the caches out.
                   2179:     &Apache::lonnet::clear_EXT_cache_status();
                   2180:     my $dbh = &Apache::lonmysql::get_dbh();
                   2181:     my $request = 'INSERT IGNORE INTO '.$weight_table.
                   2182:         "(symb_id,part_id,weight) VALUES ";
                   2183:     my $weight;
1.144     matthew  2184:     foreach my $res (@resources) {
                   2185:         my $symb_id = &get_symb_id($res->symb);
                   2186:         foreach my $part (@{$res->parts}) {
1.127     matthew  2187:             my $part_id = &get_part_id($part);
                   2188:             $weight = &Apache::lonnet::EXT('resource.'.$part.'.weight',
1.144     matthew  2189:                                            $res->symb,
1.127     matthew  2190:                                            undef,undef,undef);
                   2191:             if (!defined($weight) || ($weight eq '')) { 
                   2192:                 $weight=1;
                   2193:             }
                   2194:             $request .= "('".$symb_id."','".$part_id."','".$weight."'),";
                   2195:         }
                   2196:     }
                   2197:     $request =~ s/(,)$//;
                   2198: #    &Apache::lonnet::logthis('request = '.$/.$request);
                   2199:     $dbh->do($request);
                   2200:     if ($dbh->err()) {
                   2201:         &Apache::lonnet::logthis("error ".$dbh->errstr().
                   2202:                                  " occured executing \n".
                   2203:                                  $request);
                   2204:     }
                   2205:     return;
                   2206: }
                   2207: 
                   2208: ##########################################################
                   2209: ##########################################################
1.61      matthew  2210: 
1.127     matthew  2211: =pod
                   2212: 
1.129     matthew  2213: =item &limit_by_start_end_times
                   2214: 
                   2215: Build SQL WHERE condition which limits the data collected by the start
                   2216: and end times provided
                   2217: 
                   2218: Inputs: $starttime, $endtime, $table
                   2219: 
                   2220: Returns: $time_limits
                   2221: 
                   2222: =cut
                   2223: 
                   2224: ##########################################################
                   2225: ##########################################################
                   2226: sub limit_by_start_end_time {
                   2227:     my ($starttime,$endtime,$table) = @_;
                   2228:     my $time_requirements = undef;
                   2229:     if (defined($starttime)) {
                   2230:         $time_requirements .= $table.".timestamp>='".$starttime."'";
                   2231:         if (defined($endtime)) {
                   2232:             $time_requirements .= " AND ".$table.".timestamp<='".$endtime."'";
                   2233:         }
                   2234:     } elsif (defined($endtime)) {
                   2235:         $time_requirements .= $table.".timestamp<='".$endtime."'";
                   2236:     }
                   2237:     return $time_requirements;
                   2238: }
                   2239: 
                   2240: ##########################################################
                   2241: ##########################################################
                   2242: 
                   2243: =pod
                   2244: 
1.127     matthew  2245: =item &limit_by_section_and_status
                   2246: 
                   2247: Build SQL WHERE condition which limits the data collected by section and
                   2248: student status.
                   2249: 
                   2250: Inputs: $Sections (array ref)
                   2251:     $enrollment (string: 'any', 'expired', 'active')
                   2252:     $tablename The name of the table that holds the student data
                   2253: 
                   2254: Returns: $student_requirements,$enrollment_requirements
                   2255: 
                   2256: =cut
                   2257: 
                   2258: ##########################################################
                   2259: ##########################################################
                   2260: sub limit_by_section_and_status {
                   2261:     my ($Sections,$enrollment,$tablename) = @_;
                   2262:     my $student_requirements = undef;
                   2263:     if ( (defined($Sections) && $Sections->[0] ne 'all')) {
                   2264:         $student_requirements = '('.
                   2265:             join(' OR ', map { $tablename.".section='".$_."'" } @$Sections
                   2266:                  ).')';
                   2267:     }
                   2268:     my $enrollment_requirements=undef;
                   2269:     if (defined($enrollment) && $enrollment ne 'Any') {
                   2270:         $enrollment_requirements = $tablename.".status='".$enrollment."'";
                   2271:     }
                   2272:     return ($student_requirements,$enrollment_requirements);
                   2273: }
                   2274: 
                   2275: ######################################################
                   2276: ######################################################
1.167     raeburn  2277:                                                                                
                   2278: =pod
                   2279:                                                                                
                   2280: =item &limit_by_group
                   2281:                                                                                
                   2282: Build SQL LEFT JOIN statement to include students_groups and groupnames tables and SQL WHERE condition which limits the data collected by group.
                   2283:                                                                                
                   2284: Inputs: $Groups (array ref)
                   2285:     $stutable   The name of the table which holds the student data.
                   2286:     $grptable   The name of the table which maps group_id to groupname.
                   2287:     $stugrptab  The name of the table which holds student group affiliations.   
                   2288: Returns: $groups_join,$group_limits
                   2289:    $groups_join  JOIN part of SQL statement (to include group related tables) 
                   2290:    $group_limits SQL WHERE condition limiting to requested groups
                   2291: =cut
                   2292: 
                   2293: sub limit_by_group {
                   2294:     my ($Groups,$stutable,$grptable,$stugrptab) = @_;
                   2295:     my $groups_join = undef;
                   2296:     my $group_limits = undef;
                   2297:     if ( (defined($Groups) && $Groups->[0] ne 'all')) {
                   2298:         $groups_join =
                   2299:           ' LEFT JOIN '.$students_groups_table.
                   2300:                      ' AS '.$stugrptab.' ON '.
                   2301:                      $stugrptab.'.student_id = '.$stutable.'.student_id'.
                   2302:           ' LEFT JOIN '.$groupnames_table.
                   2303:                      ' AS '.$grptable.' ON '.
                   2304:                      $stugrptab.'.group_id = '.$grptable.'.group_id ';
                   2305:         $group_limits =
                   2306:           ' ('.
                   2307:              join(' OR ', map {  "$grptable.groupname='".$_."'" } @$Groups
                   2308:            ).')';
                   2309:     }
                   2310:     return ($groups_join,$group_limits);
                   2311: }
1.127     matthew  2312: 
                   2313: =pod
                   2314: 
                   2315: =item rank_students_by_scores_on_resources
                   2316: 
                   2317: Inputs: 
                   2318:     $resources: array ref of hash ref.  Each hash ref needs key 'symb'.
                   2319:     $Sections: array ref of sections to include,
1.167     raeburn  2320:     $Groups: array ref of groups to include.
1.127     matthew  2321:     $enrollment: string,
                   2322:     $courseid (may be omitted)
1.154     bowersj2 2323:     $starttime (may be omitted)
                   2324:     $endtime (may be omitted)
                   2325:     $has_award_for (may be omitted)
1.127     matthew  2326: 
                   2327: Returns; An array of arrays.  The sub arrays contain a student name and
1.154     bowersj2 2328: their score on the resources. $starttime and $endtime constrain the
                   2329: list to awards obtained during the given time limits. $has_score_on
                   2330: constrains the list to those students who at least attempted the
                   2331: resource identified by the given symb, which is used to filter out
                   2332: such students for statistics that would be adversely affected by such
                   2333: students. 
1.127     matthew  2334: 
                   2335: =cut
                   2336: 
                   2337: ######################################################
                   2338: ######################################################
                   2339: sub RNK_student { return 0; };
                   2340: sub RNK_score   { return 1; };
                   2341: 
                   2342: sub rank_students_by_scores_on_resources {
1.167     raeburn  2343:     my ($resources,$Sections,$Groups,$enrollment,$courseid,$starttime,$endtime,
                   2344:         $has_award_for) = @_;
1.127     matthew  2345:     return if (! defined($resources) || ! ref($resources) eq 'ARRAY');
                   2346:     if (! defined($courseid)) {
1.146     albertel 2347:         $courseid = $env{'request.course.id'};
1.127     matthew  2348:     }
                   2349:     #
                   2350:     &setup_table_names($courseid);
                   2351:     my $dbh = &Apache::lonmysql::get_dbh();
                   2352:     my ($section_limits,$enrollment_limits)=
                   2353:         &limit_by_section_and_status($Sections,$enrollment,'b');
1.167     raeburn  2354:     my ($groups_join,$group_limits) = &limit_by_group($Groups,'b','c','d');
1.127     matthew  2355:     my $symb_limits = '('.join(' OR ',map {'a.symb_id='.&get_symb_id($_);
                   2356:                                        } @$resources
                   2357:                                ).')';
1.154     bowersj2 2358:     my ($award_col, $award_join, $award_clause) = ('', '', '');
1.155     albertel 2359:     if ($has_award_for) {
1.154     bowersj2 2360:         my $resource_id = &get_symb_id($has_award_for);
                   2361:         $award_col = ", perf.awarded";
                   2362:         $award_join = "LEFT JOIN $performance_table AS perf ON perf.symb_id"
                   2363:             ." = $resource_id AND perf.student_id = b.student_id ";
                   2364:         $award_clause = "AND perf.awarded IS NOT NULL";
                   2365:     }
1.130     matthew  2366:     my $time_limits = &limit_by_start_end_time($starttime,$endtime,'a');
1.154     bowersj2 2367:     my $request = "SELECT b.student,SUM(a.awarded*w.weight) AS score "
                   2368:         ."$award_col FROM $performance_table AS a ".
                   2369:         "NATURAL LEFT JOIN $weight_table AS w ".
                   2370:         "LEFT JOIN $student_table AS b ON a.student_id=b.student_id ".
1.167     raeburn  2371:         "$award_join $groups_join "; 
                   2372:     my $limits;
1.127     matthew  2373:     if (defined($section_limits)) {
1.167     raeburn  2374:         $limits .= $section_limits.' AND ';
1.127     matthew  2375:     }
                   2376:     if (defined($enrollment_limits)) {
1.167     raeburn  2377:         $limits .= $enrollment_limits.' AND ';
1.127     matthew  2378:     }
1.130     matthew  2379:     if (defined($time_limits)) {
1.167     raeburn  2380:         $limits .= $time_limits.' AND ';
1.130     matthew  2381:     }
1.127     matthew  2382:     if ($symb_limits ne '()') {
1.167     raeburn  2383:         $limits .= $symb_limits.' AND ';
                   2384:     }
                   2385:     if (defined($group_limits)) {
                   2386:         $limits .= $group_limits.' AND ';
1.127     matthew  2387:     }
1.167     raeburn  2388:     if ($limits) {
                   2389:         $limits =~ s/( AND )$//;   # Remove extra conjunction
                   2390:         $request .= "WHERE $limits";
                   2391:     } 
1.154     bowersj2 2392:     $request .= " $award_clause GROUP BY a.student_id ORDER BY score";
1.127     matthew  2393:     #&Apache::lonnet::logthis('request = '.$/.$request);
1.154     bowersj2 2394:     my $sth = $dbh->prepare($request) or die "Can't prepare $request";
1.127     matthew  2395:     $sth->execute();
                   2396:     my $rows = $sth->fetchall_arrayref();
                   2397:     return ($rows);
                   2398: }
                   2399: 
                   2400: ########################################################
                   2401: ########################################################
                   2402: 
                   2403: =pod
                   2404: 
                   2405: =item &get_sum_of_scores
                   2406: 
                   2407: Inputs: $resource (hash ref, needs {'symb'} key),
                   2408: $part, (the part id),
                   2409: $students (array ref, contents of array are scalars holding 'sname:sdom'),
                   2410: $courseid
                   2411: 
                   2412: Returns: the sum of the score on the problem part over the students and the
                   2413:    maximum possible value for the sum (taken from the weight table).
                   2414: 
                   2415: =cut
                   2416: 
                   2417: ########################################################
                   2418: ########################################################
                   2419: sub get_sum_of_scores {
1.143     matthew  2420:     my ($symb,$part,$students,$courseid,$starttime,$endtime) = @_;
1.127     matthew  2421:     if (! defined($courseid)) {
1.146     albertel 2422:         $courseid = $env{'request.course.id'};
1.127     matthew  2423:     }
1.138     matthew  2424:     if (defined($students) && 
                   2425:         ((@$students == 0) ||
                   2426:          (@$students == 1 && (! defined($students->[0]) || 
                   2427:                               $students->[0] eq ''))
                   2428:          )
                   2429:         ){
                   2430:         undef($students);
                   2431:     }
1.127     matthew  2432:     #
                   2433:     &setup_table_names($courseid);
                   2434:     my $dbh = &Apache::lonmysql::get_dbh();
1.130     matthew  2435:     my $time_limits = &limit_by_start_end_time($starttime,$endtime,'a');
1.127     matthew  2436:     my $request = 'SELECT SUM(a.awarded*w.weight),SUM(w.weight) FROM '.
                   2437:         $performance_table.' AS a '.
                   2438:         'NATURAL LEFT JOIN '.$weight_table.' AS w ';
1.143     matthew  2439:     $request .= 'WHERE a.symb_id='.&get_symb_id($symb).
1.127     matthew  2440:         ' AND a.part_id='.&get_part_id($part);
1.130     matthew  2441:     if (defined($time_limits)) {
                   2442:         $request .= ' AND '.$time_limits;
                   2443:     }
1.127     matthew  2444:     if (defined($students)) {
                   2445:         $request .= ' AND ('.
                   2446:             join(' OR ',map {'a.student_id='.&get_student_id(split(':',$_));
                   2447:                          } @$students).
                   2448:                              ')';
                   2449:     }
                   2450:     my $sth = $dbh->prepare($request);
                   2451:     $sth->execute();
                   2452:     my $rows = $sth->fetchrow_arrayref();
                   2453:     if ($dbh->err) {
1.138     matthew  2454:         &Apache::lonnet::logthis('error 1 = '.$dbh->errstr());
                   2455:         &Apache::lonnet::logthis('prepared then executed, fetchrow_arrayrefed'.
                   2456:                                  $/.$request);
1.127     matthew  2457:         return (undef,undef);
                   2458:     }
                   2459:     return ($rows->[0],$rows->[1]);
                   2460: }
                   2461: 
1.129     matthew  2462: ########################################################
                   2463: ########################################################
                   2464: 
                   2465: =pod
                   2466: 
                   2467: =item &score_stats
                   2468: 
                   2469: Inputs: $Sections, $enrollment, $symbs, $starttime,
                   2470:         $endtime, $courseid
                   2471: 
                   2472: $Sections, $enrollment, $starttime, $endtime, and $courseid are the same as 
                   2473: elsewhere in this module.  
                   2474: $symbs is an array ref of symbs
                   2475: 
                   2476: Returns: minimum, maximum, mean, s.d., number of students, and maximum
                   2477:   possible of student scores on the given resources
                   2478: 
                   2479: =cut
                   2480: 
                   2481: ########################################################
                   2482: ########################################################
                   2483: sub score_stats {
1.167     raeburn  2484:     my ($Sections,$Groups,$enrollment,$symbs,$starttime,$endtime,$courseid)=@_;
1.129     matthew  2485:     if (! defined($courseid)) {
1.146     albertel 2486:         $courseid = $env{'request.course.id'};
1.129     matthew  2487:     }
                   2488:     #
                   2489:     &setup_table_names($courseid);
                   2490:     my $dbh = &Apache::lonmysql::get_dbh();
                   2491:     #
                   2492:     my ($section_limits,$enrollment_limits)=
                   2493:         &limit_by_section_and_status($Sections,$enrollment,'b');
1.167     raeburn  2494:     my ($groups_join,$group_limits) = &limit_by_group($Groups,'b','c','d');
1.129     matthew  2495:     my $time_limits = &limit_by_start_end_time($starttime,$endtime,'a');
                   2496:     my @Symbids = map { &get_symb_id($_); } @{$symbs};
                   2497:     #
                   2498:     my $stats_table = $courseid.'_problem_stats';
                   2499:     my $symb_restriction = join(' OR ',map {'a.symb_id='.$_;} @Symbids);
                   2500:     my $request = 'DROP TABLE '.$stats_table;
                   2501:     $dbh->do($request);
                   2502:     $request = 
                   2503:         'CREATE TEMPORARY TABLE '.$stats_table.' '.
                   2504:         'SELECT a.student_id,'.
                   2505:         'SUM(a.awarded*w.weight) AS score FROM '.
                   2506:         $performance_table.' AS a '.
                   2507:         'NATURAL LEFT JOIN '.$weight_table.' AS w '.
                   2508:         'LEFT JOIN '.$student_table.' AS b ON a.student_id=b.student_id '.
1.167     raeburn  2509:         $groups_join;
                   2510:     my $limit = ' WHERE ('.$symb_restriction.')';
1.129     matthew  2511:     if ($time_limits) {
1.167     raeburn  2512:         $limit .= ' AND '.$time_limits;
1.129     matthew  2513:     }
                   2514:     if ($section_limits) {
1.167     raeburn  2515:         $limit .= ' AND '.$section_limits;
1.129     matthew  2516:     }
                   2517:     if ($enrollment_limits) {
1.167     raeburn  2518:         $limit .= ' AND '.$enrollment_limits;
1.129     matthew  2519:     }
1.167     raeburn  2520:     if ($group_limits) {
                   2521:         $limit .= ' AND '.$group_limits;
                   2522:     }
                   2523:     $request .= $limit.' GROUP BY a.student_id';
1.129     matthew  2524: #    &Apache::lonnet::logthis('request = '.$/.$request);
                   2525:     my $sth = $dbh->prepare($request);
                   2526:     $sth->execute();
                   2527:     $request = 
                   2528:         'SELECT AVG(score),STD(score),MAX(score),MIN(score),COUNT(score) '.
                   2529:         'FROM '.$stats_table;
                   2530:     my ($ave,$std,$max,$min,$count) = &execute_SQL_request($dbh,$request);
                   2531: #    &Apache::lonnet::logthis('request = '.$/.$request);
                   2532:     
                   2533:     $request = 'SELECT SUM(weight) FROM '.$weight_table.
1.152     bowersj2 2534:         ' AS a WHERE ('.$symb_restriction.')';
1.129     matthew  2535:     my ($max_possible) = &execute_SQL_request($dbh,$request);
                   2536:     # &Apache::lonnet::logthis('request = '.$/.$request);
                   2537:     return($min,$max,$ave,$std,$count,$max_possible);
                   2538: }
                   2539: 
                   2540: 
                   2541: ########################################################
                   2542: ########################################################
                   2543: 
                   2544: =pod
                   2545: 
                   2546: =item &count_stats
                   2547: 
1.167     raeburn  2548: Inputs: $Sections, $Groups, $enrollment, $symbs, $starttime,
1.129     matthew  2549:         $endtime, $courseid
                   2550: 
1.167     raeburn  2551: $Sections, $Groups $enrollment, $starttime, $endtime, and $courseid are the 
                   2552: same as elsewhere in this module.  
1.129     matthew  2553: $symbs is an array ref of symbs
                   2554: 
                   2555: Returns: minimum, maximum, mean, s.d., and number of students
                   2556:   of the number of items correct on the given resources
                   2557: 
                   2558: =cut
                   2559: 
                   2560: ########################################################
                   2561: ########################################################
                   2562: sub count_stats {
1.167     raeburn  2563:     my ($Sections,$Groups,$enrollment,$symbs,$starttime,$endtime,$courseid)=@_;
1.129     matthew  2564:     if (! defined($courseid)) {
1.146     albertel 2565:         $courseid = $env{'request.course.id'};
1.129     matthew  2566:     }
                   2567:     #
                   2568:     &setup_table_names($courseid);
                   2569:     my $dbh = &Apache::lonmysql::get_dbh();
                   2570:     #
                   2571:     my ($section_limits,$enrollment_limits)=
                   2572:         &limit_by_section_and_status($Sections,$enrollment,'b');
1.167     raeburn  2573:     my ($groups_join,$group_limits) = &limit_by_group($Groups,'b','c','d');
1.129     matthew  2574:     my $time_limits = &limit_by_start_end_time($starttime,$endtime,'a');
                   2575:     my @Symbids = map { &get_symb_id($_); } @{$symbs};
                   2576:     #
                   2577:     my $stats_table = $courseid.'_problem_stats';
                   2578:     my $symb_restriction = join(' OR ',map {'a.symb_id='.$_;} @Symbids);
                   2579:     my $request = 'DROP TABLE '.$stats_table;
                   2580:     $dbh->do($request);
                   2581:     $request = 
                   2582:         'CREATE TEMPORARY TABLE '.$stats_table.' '.
                   2583:         'SELECT a.student_id,'.
1.151     albertel 2584:         'SUM(a.awarded) AS count FROM '.
1.129     matthew  2585:         $performance_table.' AS a '.
                   2586:         'LEFT JOIN '.$student_table.' AS b ON a.student_id=b.student_id '.
1.167     raeburn  2587:         $groups_join;
                   2588:     my $limit =  ' WHERE ('.$symb_restriction.')';
1.129     matthew  2589:     if ($time_limits) {
1.167     raeburn  2590:         $limit .= ' AND '.$time_limits;
1.129     matthew  2591:     }
                   2592:     if ($section_limits) {
1.167     raeburn  2593:         $limit .= ' AND '.$section_limits;
1.129     matthew  2594:     }
                   2595:     if ($enrollment_limits) {
1.167     raeburn  2596:         $limit .= ' AND '.$enrollment_limits;
1.129     matthew  2597:     }
1.167     raeburn  2598:     if ($group_limits) {
1.168     raeburn  2599:         $limit .= ' AND '.$group_limits;
1.167     raeburn  2600:     }
                   2601:     $request .= $limit.' GROUP BY a.student_id';
1.131     matthew  2602: #    &Apache::lonnet::logthis('request = '.$/.$request);
1.129     matthew  2603:     my $sth = $dbh->prepare($request);
                   2604:     $sth->execute();
                   2605:     $request = 
                   2606:         'SELECT AVG(count),STD(count),MAX(count),MIN(count),COUNT(count) '.
                   2607:         'FROM '.$stats_table;
                   2608:     my ($ave,$std,$max,$min,$count) = &execute_SQL_request($dbh,$request);
1.131     matthew  2609: #    &Apache::lonnet::logthis('request = '.$/.$request);
1.129     matthew  2610:     return($min,$max,$ave,$std,$count);
                   2611: }
1.127     matthew  2612: 
                   2613: ######################################################
                   2614: ######################################################
                   2615: 
                   2616: =pod
                   2617: 
                   2618: =item get_student_data
                   2619: 
                   2620: =cut
                   2621: 
                   2622: ######################################################
                   2623: ######################################################
1.105     matthew  2624: sub get_student_data {
                   2625:     my ($students,$courseid) = @_;
1.146     albertel 2626:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.105     matthew  2627:     &setup_table_names($courseid);
                   2628:     my $dbh = &Apache::lonmysql::get_dbh();
                   2629:     return undef if (! defined($dbh));
                   2630:     my $request = 'SELECT '.
                   2631:         'student_id, student '.
                   2632:         'FROM '.$student_table;
                   2633:     if (defined($students)) {
                   2634:         $request .= ' WHERE ('.
                   2635:             join(' OR ', map {'student_id='.
                   2636:                                   &get_student_id($_->{'username'},
                   2637:                                                   $_->{'domain'})
                   2638:                               } @$students
                   2639:                  ).')';
                   2640:     }
                   2641:     $request.= ' ORDER BY student_id';
                   2642:     my $sth = $dbh->prepare($request);
                   2643:     $sth->execute();
                   2644:     if ($dbh->err) {
1.138     matthew  2645:         &Apache::lonnet::logthis('error 2 = '.$dbh->errstr());
                   2646:         &Apache::lonnet::logthis('prepared then executed '.$/.$request);
1.105     matthew  2647:         return undef;
                   2648:     }
                   2649:     my $dataset = $sth->fetchall_arrayref();
                   2650:     if (ref($dataset) eq 'ARRAY' && scalar(@$dataset)>0) {
                   2651:         return $dataset;
                   2652:     }
                   2653: }
                   2654: 
1.159     albertel 2655: sub RD_student_id      { return 0; }
                   2656: sub RD_awarddetail     { return 1; }
                   2657: sub RD_response_eval   { return 2; }
                   2658: sub RD_response_eval_2 { return 3; }
                   2659: sub RD_submission      { return 4; }
                   2660: sub RD_timestamp       { return 5; }
                   2661: sub RD_tries           { return 6; }
                   2662: sub RD_sname           { return 7; }
1.108     matthew  2663: 
                   2664: sub get_response_data {
1.167     raeburn  2665:     my ($Sections,$Groups,$enrollment,$symb,$response,$courseid) = @_;
1.103     matthew  2666:     return undef if (! defined($symb) || 
1.100     matthew  2667:                ! defined($response));
1.146     albertel 2668:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.100     matthew  2669:     #
                   2670:     &setup_table_names($courseid);
                   2671:     my $symb_id = &get_symb_id($symb);
1.137     matthew  2672:     if (! defined($symb_id)) {
                   2673:         &Apache::lonnet::logthis('Unable to find symb for '.$symb.' in '.$courseid);
                   2674:         return undef;
                   2675:     }
1.100     matthew  2676:     my $response_id = &get_part_id($response);
1.137     matthew  2677:     if (! defined($response_id)) {
                   2678:         &Apache::lonnet::logthis('Unable to find id for '.$response.' in '.$courseid);
                   2679:         return undef;
                   2680:     }
1.100     matthew  2681:     #
                   2682:     my $dbh = &Apache::lonmysql::get_dbh();
                   2683:     return undef if (! defined($dbh));
1.126     matthew  2684:     #
1.127     matthew  2685:     my ($student_requirements,$enrollment_requirements) = 
                   2686:         &limit_by_section_and_status($Sections,$enrollment,'d');
1.167     raeburn  2687:     my ($groups_join,$group_limits) = &limit_by_group($Groups,'d','e','f');
1.100     matthew  2688:     my $request = 'SELECT '.
1.105     matthew  2689:         'a.student_id, a.awarddetail, a.response_specific_value, '.
1.159     albertel 2690:         'a.response_specific_value_2, a.submission, b.timestamp, '.
                   2691: 	'c.tries, d.student '.
1.100     matthew  2692:         'FROM '.$fulldump_response_table.' AS a '.
                   2693:         'LEFT JOIN '.$fulldump_timestamp_table.' AS b '.
                   2694:         'ON a.symb_id=b.symb_id AND a.student_id=b.student_id AND '.
                   2695:         'a.transaction = b.transaction '.
                   2696:         'LEFT JOIN '.$fulldump_part_table.' AS c '.
                   2697:         'ON a.symb_id=c.symb_id AND a.student_id=c.student_id AND '.        
                   2698:         'a.part_id=c.part_id AND a.transaction = c.transaction '.
1.108     matthew  2699:         'LEFT JOIN '.$student_table.' AS d '.
                   2700:         'ON a.student_id=d.student_id '.
1.167     raeburn  2701:         $groups_join;
                   2702:     my $limit = ' WHERE '.
1.100     matthew  2703:         'a.symb_id='.$symb_id.' AND a.response_id='.$response_id;
1.167     raeburn  2704:     if (defined($student_requirements)) {
                   2705:         $limit .= ' AND '.$student_requirements;
                   2706:     }
                   2707:     if (defined($enrollment_requirements)) {
                   2708:         $limit .= ' AND '.$enrollment_requirements;
                   2709:     }
                   2710:     if (defined($group_limits)) {
1.168     raeburn  2711:         $limit .= ' AND '.$group_limits;
1.100     matthew  2712:     }
1.167     raeburn  2713:     $request .= $limit.' ORDER BY b.timestamp';
1.103     matthew  2714: #    &Apache::lonnet::logthis("request =\n".$request);
1.100     matthew  2715:     my $sth = $dbh->prepare($request);
                   2716:     $sth->execute();
1.105     matthew  2717:     if ($dbh->err) {
1.138     matthew  2718:         &Apache::lonnet::logthis('error 3 = '.$dbh->errstr());
                   2719:         &Apache::lonnet::logthis('prepared then executed '.$/.$request);
1.105     matthew  2720:         return undef;
                   2721:     }
1.100     matthew  2722:     my $dataset = $sth->fetchall_arrayref();
                   2723:     if (ref($dataset) eq 'ARRAY' && scalar(@$dataset)>0) {
1.117     matthew  2724:         # Clear the \'s from around the submission
                   2725:         for (my $i =0;$i<scalar(@$dataset);$i++) {
                   2726:             $dataset->[$i]->[3] =~ s/(\'$|^\')//g;
                   2727:         }
1.103     matthew  2728:         return $dataset;
1.100     matthew  2729:     }
1.118     matthew  2730: }
                   2731: 
                   2732: 
1.159     albertel 2733: sub RDs_awarddetail     { return 3; }
                   2734: sub RDs_submission      { return 2; }
                   2735: sub RDs_timestamp       { return 1; }
                   2736: sub RDs_tries           { return 0; }
                   2737: sub RDs_awarded         { return 4; }
                   2738: sub RDs_response_eval   { return 5; }
                   2739: sub RDs_response_eval_2 { return 6; }
1.160     albertel 2740: sub RDs_part_award      { return 7; }
1.118     matthew  2741: 
                   2742: sub get_response_data_by_student {
                   2743:     my ($student,$symb,$response,$courseid) = @_;
                   2744:     return undef if (! defined($symb) || 
                   2745:                      ! defined($response));
1.146     albertel 2746:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.118     matthew  2747:     #
                   2748:     &setup_table_names($courseid);
                   2749:     my $symb_id = &get_symb_id($symb);
                   2750:     my $response_id = &get_part_id($response);
                   2751:     #
                   2752:     my $student_id = &get_student_id($student->{'username'},
                   2753:                                      $student->{'domain'});
                   2754:     #
                   2755:     my $dbh = &Apache::lonmysql::get_dbh();
                   2756:     return undef if (! defined($dbh));
                   2757:     my $request = 'SELECT '.
1.159     albertel 2758:         'c.tries, b.timestamp, a.submission, a.awarddetail, c.awarded, '.
1.160     albertel 2759: 	'a.response_specific_value, a.response_specific_value_2, c.award '.
1.118     matthew  2760:         'FROM '.$fulldump_response_table.' AS a '.
                   2761:         'LEFT JOIN '.$fulldump_timestamp_table.' AS b '.
                   2762:         'ON a.symb_id=b.symb_id AND a.student_id=b.student_id AND '.
                   2763:         'a.transaction = b.transaction '.
                   2764:         'LEFT JOIN '.$fulldump_part_table.' AS c '.
                   2765:         'ON a.symb_id=c.symb_id AND a.student_id=c.student_id AND '.        
                   2766:         'a.part_id=c.part_id AND a.transaction = c.transaction '.
                   2767:         'LEFT JOIN '.$student_table.' AS d '.
                   2768:         'ON a.student_id=d.student_id '.
1.119     matthew  2769:         'LEFT JOIN '.$performance_table.' AS e '.
                   2770:         'ON a.symb_id=e.symb_id AND a.part_id=e.part_id AND '.
                   2771:         'a.student_id=e.student_id AND c.tries=e.tries '.
1.118     matthew  2772:         'WHERE '.
                   2773:         'a.symb_id='.$symb_id.' AND a.response_id='.$response_id.
                   2774:         ' AND a.student_id='.$student_id.' ORDER BY b.timestamp';
1.125     matthew  2775: #    &Apache::lonnet::logthis("request =\n".$request);
1.118     matthew  2776:     my $sth = $dbh->prepare($request);
                   2777:     $sth->execute();
                   2778:     if ($dbh->err) {
1.138     matthew  2779:         &Apache::lonnet::logthis('error 4 = '.$dbh->errstr());
                   2780:         &Apache::lonnet::logthis('prepared then executed '.$/.$request);
1.118     matthew  2781:         return undef;
                   2782:     }
                   2783:     my $dataset = $sth->fetchall_arrayref();
                   2784:     if (ref($dataset) eq 'ARRAY' && scalar(@$dataset)>0) {
                   2785:         # Clear the \'s from around the submission
                   2786:         for (my $i =0;$i<scalar(@$dataset);$i++) {
                   2787:             $dataset->[$i]->[2] =~ s/(\'$|^\')//g;
                   2788:         }
                   2789:         return $dataset;
                   2790:     }
                   2791:     return undef; # error occurred
1.106     matthew  2792: }
1.108     matthew  2793: 
                   2794: sub RT_student_id { return 0; }
                   2795: sub RT_awarded    { return 1; }
                   2796: sub RT_tries      { return 2; }
                   2797: sub RT_timestamp  { return 3; }
1.106     matthew  2798: 
                   2799: sub get_response_time_data {
1.167     raeburn  2800:     my ($sections,$groups,$enrollment,$symb,$part,$courseid) = @_;
1.106     matthew  2801:     return undef if (! defined($symb) || 
1.107     matthew  2802:                      ! defined($part));
1.146     albertel 2803:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.106     matthew  2804:     #
                   2805:     &setup_table_names($courseid);
                   2806:     my $symb_id = &get_symb_id($symb);
1.142     matthew  2807:     if (! defined($symb_id)) {
                   2808:         &Apache::lonnet::logthis('Unable to find symb for '.$symb.' in '.$courseid);
                   2809:         return undef;
                   2810:     }
1.107     matthew  2811:     my $part_id = &get_part_id($part);
1.142     matthew  2812:     if (! defined($part_id)) {
                   2813:         &Apache::lonnet::logthis('Unable to find id for '.$part.' in '.$courseid);
                   2814:         return undef;
                   2815:     }
1.106     matthew  2816:     #
                   2817:     my $dbh = &Apache::lonmysql::get_dbh();
                   2818:     return undef if (! defined($dbh));
1.142     matthew  2819:     my ($student_requirements,$enrollment_requirements) = 
                   2820:         &limit_by_section_and_status($sections,$enrollment,'d');
1.167     raeburn  2821:     my ($groups_join,$group_limits) = &limit_by_group($groups,'d','e','f');
1.106     matthew  2822:     my $request = 'SELECT '.
1.107     matthew  2823:         'a.student_id, a.awarded, a.tries, b.timestamp '.
                   2824:         'FROM '.$fulldump_part_table.' AS a '.
1.142     matthew  2825:         'LEFT JOIN '.$fulldump_timestamp_table.' AS b '.
                   2826:         'ON a.symb_id=b.symb_id AND a.student_id=b.student_id AND '.
                   2827:         'a.transaction = b.transaction '.
                   2828:         'LEFT JOIN '.$student_table.' as d '.
                   2829:         'ON a.student_id=d.student_id '.
1.167     raeburn  2830:         $groups_join;
                   2831:     my $limit = ' WHERE '.
1.107     matthew  2832:         'a.symb_id='.$symb_id.' AND a.part_id='.$part_id;
1.167     raeburn  2833:     if (defined($student_requirements)) {
                   2834:         $limit .= ' AND '.$student_requirements;
                   2835:     }
                   2836:     if (defined($enrollment_requirements)) {
                   2837:         $limit .= ' AND '.$enrollment_requirements;
                   2838:     }
                   2839:     if (defined($group_limits)) {
                   2840:         $limit .= ' AND '.$group_limits;  
1.106     matthew  2841:     }
1.167     raeburn  2842:     $request .= $limit.' ORDER BY b.timestamp';
1.106     matthew  2843: #    &Apache::lonnet::logthis("request =\n".$request);
                   2844:     my $sth = $dbh->prepare($request);
                   2845:     $sth->execute();
                   2846:     if ($dbh->err) {
1.138     matthew  2847:         &Apache::lonnet::logthis('error 5 = '.$dbh->errstr());
                   2848:         &Apache::lonnet::logthis('prepared then executed '.$/.$request);
1.106     matthew  2849:         return undef;
                   2850:     }
                   2851:     my $dataset = $sth->fetchall_arrayref();
                   2852:     if (ref($dataset) eq 'ARRAY' && scalar(@$dataset)>0) {
                   2853:         return $dataset;
                   2854:     }
                   2855: 
1.100     matthew  2856: }
1.61      matthew  2857: 
                   2858: ################################################
                   2859: ################################################
                   2860: 
                   2861: =pod
                   2862: 
1.167     raeburn  2863: =item &get_student_scores($Sections,$Groups,$Symbs,$enrollment,$courseid)
1.113     matthew  2864: 
                   2865: =cut
                   2866: 
                   2867: ################################################
                   2868: ################################################
                   2869: sub get_student_scores {
1.167     raeburn  2870:     my ($sections,$groups,$Symbs,$enrollment,$courseid,$starttime,$endtime) = @_;
1.146     albertel 2871:     $courseid = $env{'request.course.id'} if (! defined($courseid));
1.113     matthew  2872:     &setup_table_names($courseid);
                   2873:     my $dbh = &Apache::lonmysql::get_dbh();
                   2874:     return (undef) if (! defined($dbh));
                   2875:     my $tmptable = $courseid.'_temp_'.time;
1.145     matthew  2876:     my $request = 'DROP TABLE IF EXISTS '.$tmptable;
                   2877: #    &Apache::lonnet::logthis('request = '.$/.$request);
                   2878:     $dbh->do($request);
1.114     matthew  2879:     #
                   2880:     my $symb_requirements;
1.113     matthew  2881:     if (defined($Symbs)  && @$Symbs) {
                   2882:         $symb_requirements = '('.
1.114     matthew  2883:             join(' OR ', map{ "(a.symb_id='".&get_symb_id($_->{'symb'}).
1.121     matthew  2884:                               "' AND a.part_id='".&get_part_id($_->{'part'}).
                   2885:                               "')"
1.113     matthew  2886:                               } @$Symbs).')';
                   2887:     }
1.114     matthew  2888:     #
1.145     matthew  2889:     my ($student_requirements,$enrollment_requirements) = 
                   2890:         &limit_by_section_and_status($sections,$enrollment,'b');
1.114     matthew  2891:     #
1.167     raeburn  2892:     my ($groups_join,$group_limits) = &limit_by_group($groups,'b','d','e');
1.145     matthew  2893:     my $time_requirements = &limit_by_start_end_time($starttime,$endtime,'a');
1.114     matthew  2894:     ##
1.145     matthew  2895:     $request = 'CREATE TEMPORARY TABLE IF NOT EXISTS '.$tmptable.
                   2896:         ' SELECT a.student_id,SUM(a.awarded*c.weight) AS score FROM '.
1.114     matthew  2897:         $performance_table.' AS a ';
1.145     matthew  2898:     $request .= "LEFT JOIN ".$weight_table.' AS c ON a.symb_id=c.symb_id AND a.part_id=c.part_id ';
1.114     matthew  2899:     if (defined($student_requirements) || defined($enrollment_requirements)) {
1.167     raeburn  2900:         $request .= ' LEFT JOIN '.$student_table.' AS b ON a.student_id=b.student_id ';
                   2901:     }
                   2902:     if (defined($groups_join)) {
                   2903:         $request .= $groups_join;
1.114     matthew  2904:     }
1.167     raeburn  2905:     if (defined($symb_requirements)       || 
                   2906:         defined($student_requirements)    ||
                   2907:         defined($enrollment_requirements) ||
                   2908:         defined($group_limits) ) {
1.113     matthew  2909:         $request .= ' WHERE ';
                   2910:     }
1.114     matthew  2911:     if (defined($symb_requirements)) {
                   2912:         $request .= $symb_requirements.' AND ';
                   2913:     }
                   2914:     if (defined($student_requirements)) {
                   2915:         $request .= $student_requirements.' AND ';
                   2916:     }
                   2917:     if (defined($enrollment_requirements)) {
                   2918:         $request .= $enrollment_requirements.' AND ';
                   2919:     }
1.121     matthew  2920:     if (defined($time_requirements)) {
                   2921:         $request .= $time_requirements.' AND ';
                   2922:     }
                   2923:     $request =~ s/ AND $//; # Strip of the trailing ' AND '.
1.114     matthew  2924:     $request .= ' GROUP BY a.student_id';
                   2925: #    &Apache::lonnet::logthis("request = \n".$request);
1.113     matthew  2926:     my $sth = $dbh->prepare($request);
                   2927:     $sth->execute();
                   2928:     if ($dbh->err) {
1.138     matthew  2929:         &Apache::lonnet::logthis('error 6 = '.$dbh->errstr());
                   2930:         &Apache::lonnet::logthis('prepared then executed '.$/.$request);
1.113     matthew  2931:         return undef;
                   2932:     }
                   2933:     $request = 'SELECT score,COUNT(*) FROM '.$tmptable.' GROUP BY score';
                   2934: #    &Apache::lonnet::logthis("request = \n".$request);
                   2935:     $sth = $dbh->prepare($request);
                   2936:     $sth->execute();
                   2937:     if ($dbh->err) {
1.138     matthew  2938:         &Apache::lonnet::logthis('error 7 = '.$dbh->errstr());
                   2939:         &Apache::lonnet::logthis('prepared then executed '.$/.$request);
1.113     matthew  2940:         return undef;
                   2941:     }
                   2942:     my $dataset = $sth->fetchall_arrayref();
                   2943:     return $dataset;
                   2944: }
                   2945: 
                   2946: ################################################
                   2947: ################################################
                   2948: 
                   2949: =pod
                   2950: 
1.61      matthew  2951: =item &setup_table_names()
                   2952: 
                   2953: input: course id
                   2954: 
                   2955: output: none
                   2956: 
                   2957: Cleans up the package variables for local caching.
                   2958: 
                   2959: =cut
                   2960: 
                   2961: ################################################
                   2962: ################################################
                   2963: sub setup_table_names {
                   2964:     my ($courseid) = @_;
                   2965:     if (! defined($courseid)) {
1.146     albertel 2966:         $courseid = $env{'request.course.id'};
1.61      matthew  2967:     }
                   2968:     #
                   2969:     if (! defined($current_course) || $current_course ne $courseid) {
                   2970:         # Clear out variables
                   2971:         $have_read_part_table = 0;
                   2972:         undef(%ids_by_part);
                   2973:         undef(%parts_by_id);
                   2974:         $have_read_symb_table = 0;
                   2975:         undef(%ids_by_symb);
                   2976:         undef(%symbs_by_id);
                   2977:         $have_read_student_table = 0;
                   2978:         undef(%ids_by_student);
                   2979:         undef(%students_by_id);
1.167     raeburn  2980:         $have_read_groupnames_table = 0;
                   2981:         undef(%ids_by_groupname);
1.61      matthew  2982:         #
                   2983:         $current_course = $courseid;
                   2984:     }
                   2985:     #
                   2986:     # Set up database names
                   2987:     my $base_id = $courseid;
1.167     raeburn  2988:     $symb_table               = $base_id.'_'.'symb';
                   2989:     $part_table               = $base_id.'_'.'part';
                   2990:     $student_table            = $base_id.'_'.'student';
                   2991:     $groupnames_table         = $base_id.'_'.'groupnames';
                   2992:     $students_groups_table    = $base_id.'_'.'studentgroups';
                   2993:     $performance_table        = $base_id.'_'.'performance';
                   2994:     $parameters_table         = $base_id.'_'.'parameters';
1.89      matthew  2995:     $fulldump_part_table      = $base_id.'_'.'partdata';
                   2996:     $fulldump_response_table  = $base_id.'_'.'responsedata';
                   2997:     $fulldump_timestamp_table = $base_id.'_'.'timestampdata';
1.127     matthew  2998:     $weight_table             = $base_id.'_'.'weight';
1.89      matthew  2999:     #
                   3000:     @Tables = (
                   3001:                $symb_table,
                   3002:                $part_table,
                   3003:                $student_table,
1.167     raeburn  3004:                $groupnames_table,
                   3005:                $students_groups_table,
1.89      matthew  3006:                $performance_table,
                   3007:                $parameters_table,
                   3008:                $fulldump_part_table,
                   3009:                $fulldump_response_table,
                   3010:                $fulldump_timestamp_table,
1.127     matthew  3011:                $weight_table,
1.89      matthew  3012:                );
1.61      matthew  3013:     return;
1.3       stredwic 3014: }
1.1       stredwic 3015: 
1.35      matthew  3016: ################################################
                   3017: ################################################
                   3018: 
                   3019: =pod
                   3020: 
1.57      matthew  3021: =back
                   3022: 
                   3023: =item End of Local Data Caching Subroutines
                   3024: 
                   3025: =cut
                   3026: 
                   3027: ################################################
                   3028: ################################################
                   3029: 
1.89      matthew  3030: } # End scope of table identifiers
1.57      matthew  3031: 
                   3032: ################################################
                   3033: ################################################
                   3034: 
                   3035: =pod
                   3036: 
                   3037: =head3 Classlist Subroutines
                   3038: 
1.35      matthew  3039: =item &get_classlist();
                   3040: 
                   3041: Retrieve the classist of a given class or of the current class.  Student
                   3042: information is returned from the classlist.db file and, if needed,
                   3043: from the students environment.
                   3044: 
1.150     albertel 3045: Optional arguments are $cdom, and $cnum (course domain,
                   3046: and course number, respectively).  If either is ommitted the course
                   3047: will be taken from the current environment ($env{'request.course.id'},
1.146     albertel 3048: $env{'course.'.$cid.'.domain'}, and $env{'course.'.$cid.'.num'}).
1.35      matthew  3049: 
                   3050: Returns a reference to a hash which contains:
                   3051:  keys    '$sname:$sdom'
1.136     raeburn  3052:  values  [$sdom,$sname,$end,$start,$id,$section,$fullname,$status,$type,$lockedtype]
1.54      bowersj2 3053: 
                   3054: The constant values CL_SDOM, CL_SNAME, CL_END, etc. can be used
                   3055: as indices into the returned list to future-proof clients against
                   3056: changes in the list order.
1.35      matthew  3057: 
                   3058: =cut
                   3059: 
                   3060: ################################################
                   3061: ################################################
1.54      bowersj2 3062: 
                   3063: sub CL_SDOM     { return 0; }
                   3064: sub CL_SNAME    { return 1; }
                   3065: sub CL_END      { return 2; }
                   3066: sub CL_START    { return 3; }
                   3067: sub CL_ID       { return 4; }
                   3068: sub CL_SECTION  { return 5; }
                   3069: sub CL_FULLNAME { return 6; }
                   3070: sub CL_STATUS   { return 7; }
1.111     raeburn  3071: sub CL_TYPE     { return 8; }
1.136     raeburn  3072: sub CL_LOCKEDTYPE   { return 9; }
1.35      matthew  3073: 
                   3074: sub get_classlist {
1.150     albertel 3075:     my ($cdom,$cnum) = @_;
                   3076:     my $cid = $cdom.'_'.$cnum;
                   3077:     if (!defined($cdom) || !defined($cnum)) {
                   3078: 	$cid =  $env{'request.course.id'};
                   3079: 	$cdom = $env{'course.'.$cid.'.domain'};
                   3080: 	$cnum = $env{'course.'.$cid.'.num'};
                   3081:     }
1.57      matthew  3082:     my $now = time;
1.35      matthew  3083:     #
                   3084:     my %classlist=&Apache::lonnet::dump('classlist',$cdom,$cnum);
                   3085:     while (my ($student,$info) = each(%classlist)) {
1.60      matthew  3086:         if ($student =~ /^(con_lost|error|no_such_host)/i) {
                   3087:             &Apache::lonnet::logthis('get_classlist error for '.$cid.':'.$student);
                   3088:             return undef;
                   3089:         }
1.35      matthew  3090:         my ($sname,$sdom) = split(/:/,$student);
                   3091:         my @Values = split(/:/,$info);
1.136     raeburn  3092:         my ($end,$start,$id,$section,$fullname,$type,$lockedtype);
1.35      matthew  3093:         if (@Values > 2) {
1.136     raeburn  3094:             ($end,$start,$id,$section,$fullname,$type,$lockedtype) = @Values;
1.35      matthew  3095:         } else { # We have to get the data ourselves
                   3096:             ($end,$start) = @Values;
1.37      matthew  3097:             $section = &Apache::lonnet::getsection($sdom,$sname,$cid);
1.35      matthew  3098:             my %info=&Apache::lonnet::get('environment',
                   3099:                                           ['firstname','middlename',
                   3100:                                            'lastname','generation','id'],
                   3101:                                           $sdom, $sname);
                   3102:             my ($tmp) = keys(%info);
                   3103:             if ($tmp =~/^(con_lost|error|no_such_host)/i) {
                   3104:                 $fullname = 'not available';
                   3105:                 $id = 'not available';
1.38      matthew  3106:                 &Apache::lonnet::logthis('unable to retrieve environment '.
                   3107:                                          'for '.$sname.':'.$sdom);
1.35      matthew  3108:             } else {
1.141     albertel 3109:                 $fullname = &Apache::lonnet::format_name(@info{qw/firstname middlename lastname generation/},'lastname');
1.35      matthew  3110:                 $id = $info{'id'};
                   3111:             }
1.36      matthew  3112:             # Update the classlist with this students information
                   3113:             if ($fullname ne 'not available') {
1.141     albertel 3114: 		my $enrolldata = join(':',$end,$start,$id,$section,$fullname);
                   3115: 		my $reply=&Apache::lonnet::cput('classlist',
1.36      matthew  3116:                                                 {$student => $enrolldata},
                   3117:                                                 $cdom,$cnum);
                   3118:                 if ($reply !~ /^(ok|delayed)/) {
                   3119:                     &Apache::lonnet::logthis('Unable to update classlist for '.
                   3120:                                              'student '.$sname.':'.$sdom.
                   3121:                                              ' error:'.$reply);
                   3122:                 }
                   3123:             }
1.35      matthew  3124:         }
                   3125:         my $status='Expired';
                   3126:         if(((!$end) || $now < $end) && ((!$start) || ($now > $start))) {
                   3127:             $status='Active';
                   3128:         }
1.174     albertel 3129:         if(($now < $start) && ((!$end) || $now < $end )) {
                   3130:             $status='Future';
                   3131:         }
1.35      matthew  3132:         $classlist{$student} = 
1.136     raeburn  3133:             [$sdom,$sname,$end,$start,$id,$section,$fullname,$status,$type,$lockedtype];
1.35      matthew  3134:     }
                   3135:     if (wantarray()) {
                   3136:         return (\%classlist,['domain','username','end','start','id',
1.136     raeburn  3137:                              'section','fullname','status','type','lockedtype']);
1.35      matthew  3138:     } else {
                   3139:         return \%classlist;
                   3140:     }
                   3141: }
                   3142: 
1.166     raeburn  3143: sub get_group_memberships {
1.170     raeburn  3144:     my ($classlist,$keylist,$cdom,$cnum) = @_;
1.172     albertel 3145: 
                   3146:     return ({},{}) if (!ref($classlist) || !ref($keylist));
                   3147: 
1.166     raeburn  3148:     my $cid = $cdom.'_'.$cnum;
                   3149:     if (!defined($cdom) || !defined($cnum)) {
                   3150:         $cid =  $env{'request.course.id'};
                   3151:         $cdom = $env{'course.'.$cid.'.domain'};
                   3152:         $cnum = $env{'course.'.$cid.'.num'};
                   3153:     }
                   3154:     my (%classgroups,%studentgroups);
                   3155:     my $now = time;
                   3156:     my $access_end = $env{'course.'.$cid.'.default_enrollment_end_date'};
1.171     raeburn  3157:     my %curr_groups =&Apache::longroup::coursegroups($cdom,$cnum);
1.169     albertel 3158:     if (%curr_groups) {
1.170     raeburn  3159:         my $grpindex = scalar(@{$keylist});
1.169     albertel 3160:         my %groupmemberhash = 
                   3161: 	    &Apache::lonnet::get_group_membership($cdom,$cnum);
1.166     raeburn  3162:         foreach my $student (keys(%{$classlist})) {
                   3163:             %{$classgroups{$student}} = ();
                   3164:             my $hasgroup = 0;
                   3165:             foreach my $status ('previous','future','active','aftercourse') {
                   3166:                 %{$classgroups{$student}{$status}} = ();
                   3167:             }
                   3168:             foreach my $group (keys(%curr_groups)) {
                   3169:                 if (defined($groupmemberhash{$group.':'.$student})) {
                   3170:                     my ($end,$start) = split(/:/,$groupmemberhash{$group.':'.
                   3171:                                                                     $student});
                   3172:                     if ($start == -1) {
                   3173:                         next;
                   3174:                     } else {
                   3175:                         $studentgroups{$group} ++;
                   3176:                         $hasgroup = 1;
                   3177:                         if ($end && $end < $now) {
                   3178:                             $classgroups{$student}{'previous'}{$group} =
                   3179:                                          $groupmemberhash{$group.':'.$student};
                   3180:                             if ($classlist->{$student}[&CL_STATUS()] eq 'Expired') {
                   3181:                                 if ($access_end && $access_end < $now) {
                   3182:                                     if ($access_end - $end < 86400) {
                   3183:                                         $classgroups{$student}{'aftercourse'}{$group} = $groupmemberhash{$group.':'.$student};
                   3184:                                     }
                   3185:                                 }
                   3186:                             }
                   3187:                         } elsif ($now > $start) {
                   3188:                             if (!$end || $end > $now) {
                   3189:                                 $classgroups{$student}{'active'}{$group} =
                   3190:                                          $groupmemberhash{$group.':'.$student};
                   3191:                             }
                   3192:                         } else {
                   3193:                             $classgroups{$student}{'future'}{$group} =
                   3194:                                          $groupmemberhash{$group.':'.$student};
                   3195:                         }
                   3196:                     }
                   3197:                 }
                   3198:             }
                   3199:             if (!$hasgroup) {
                   3200:                 $studentgroups{'none'} ++;
1.170     raeburn  3201:             } else {
                   3202:                 $classlist->{$student}->[$grpindex] = join(',',
                   3203:                               sort(keys(%{$classgroups{$student}{'active'}})));
1.166     raeburn  3204:             }
                   3205:         }
                   3206:     }
                   3207:     return (\%classgroups,\%studentgroups);
                   3208: }
                   3209:                                                                                    
                   3210: sub get_students_groups {
                   3211:     my ($student,$enrollment_status,$classgroups) = @_;
                   3212:     my @studentsgroups = ();
                   3213:     if (ref($$classgroups{$student}{'active'}) eq 'HASH') {
                   3214:         push(@studentsgroups,keys(%{$$classgroups{$student}{'active'}}));
                   3215:     }
                   3216:     if ($enrollment_status eq 'Any') {
                   3217:         foreach my $status ('previous','future') {
                   3218:             if (ref($$classgroups{$student}{$status}) eq 'HASH') {
                   3219:                 push(@studentsgroups,keys(%{$$classgroups{$student}{$status}}));
                   3220:             }
                   3221:         }
                   3222:     } else {
                   3223:         if (ref($$classgroups{$student}{'aftercourse'}) eq 'HASH') {
                   3224:             push(@studentsgroups,keys(%{$$classgroups{$student}{'aftercourse'}}));
                   3225:         }
                   3226:     }
                   3227:     return @studentsgroups;
                   3228: }
                   3229: 
                   3230: 
1.1       stredwic 3231: # ----- END HELPER FUNCTIONS --------------------------------------------
                   3232: 
                   3233: 1;
                   3234: __END__
1.36      matthew  3235: 

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