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

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

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